2017-07-21 19 views
1

Ajax呼び出しを使用してドキュメントを更新する必要がありますが、コントローラに渡されたモデルへのAjax呼び出しからデータをバインドすると失敗しました。Ajaxポストからコントローラへ渡されたモデルへのバインドデータ

私はここで間違っていますか?

また、以下のNullReferenceExceptionを回避する文字列を期待するようにコントローラの定義を変更しようとしましたが、文字列はnullとして渡されます。

要求ペイロード

{"model":{"Text":"Test","LastUpdated":null,"TrainingSentiment":"Test","Sentiment":"Test","SentimentScore":"-1","Entities":[{"Start":0,"End":0,"Value":"Test","Orth":"Test","Label":"Test"}]}} 

プレビュー

System.NullReferenceException: Object reference not set to an instance of an object. 
    at Microsoft.Azure.Documents.Document.get_AttachmentsLink() 
    at Microsoft.Extensions.Internal.PropertyHelper.CallNullSafePropertyGetter[TDeclaringType,TValue](Func`2 getter, Object target) 
    at Microsoft.AspNetCore.Mvc.Internal.DefaultComplexObjectValidationStrategy.Enumerator.MoveNext() 
    at Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitChildren(IValidationStrategy strategy) 
    at Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitComplexType() 
    at Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.Visit(ModelMetadata metadata, String key, Object model) 
    at Microsoft.AspNetCore.Mvc.Internal.DefaultControllerArgumentBinder.<BindModelAsync>d__8.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
    at Microsoft.AspNetCore.Mvc.Internal.DefaultControllerArgumentBinder.<BindArgumentsCoreAsync>d__6.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context) 
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) 
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
    at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
    at Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware.<ExecuteWithFilter>d__7.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
    at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext() 

アヤックス

var modelObj = { 
    model: { 
     Text: "Test", 
     LastUpdated: null, 
     TrainingSentiment: "Test", 
     Sentiment: "Test", 
     SentimentScore: "-1", 
     Entities: [ 
      { 
       Start: 0, 
       End: 0, 
       Value: "Test", 
       Orth: "Test", 
       Label: "Test" 
      } 
     ] 
    } 
}; 

$.ajax({ 
    type: "POST", 
    url: '/Tweets/DocumentUpdateAjax', 
    contentType: "application/json", 
    data: JSON.stringify(modelObj), 
    dataType: "html", 
    success: function (response) { 
     console.log("Success!"); 

     /** Replace the partial view with html contents from the response. **/ 
     $("#updateDocumentPartialView").html(response); 

    }, 
    failure: function (response) { 
     console.log("Failure!"); 

     /** Dump the JSON string to the console. **/ 
     console.log(JSON.stringify(response)); 
    }, 
    error: function (response) { 
     console.log("Error!"); 

     /** Dump the JSON string to the console. **/ 
     console.log(JSON.stringify(response)); 
    } 
}); 

コントローラー

[HttpPost] 
public IActionResult DocumentUpdateAjax(TrainingModel model) 
{ 
    .... 
} 

モデル

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Http; 
using Newtonsoft.Json; 

namespace TextualAnalytics.Models 
{ 
    public class TrainingModel : Microsoft.Azure.Documents.Document 
    { 

     [JsonProperty(PropertyName = "text")] 
     public string Text { get; set; } 

     [JsonProperty(PropertyName = "last_updated")] 
     public DateTime? LastUpdated { get; set; } 

     [JsonProperty(PropertyName = "training_sentiment")] 
     public string TrainingSentiment { get; set; } 

     [JsonProperty(PropertyName = "sentiment")] 
     public string Sentiment { get; set; } 

     [JsonProperty(PropertyName = "sentiment_score")] 
     public string SentimentScore { get; set; } 

     [JsonProperty(PropertyName = "entities")] 
     public List<Entity> Entities { get; set; } 

     public class Entity 
     { 

      [JsonProperty(PropertyName = "start")] 
      public long Start { get; set; } 

      [JsonProperty(PropertyName = "end")] 
      public long End { get; set; } 

      [JsonProperty(PropertyName = "value")] 
      public string Value { get; set; } 

      [JsonProperty(PropertyName = "orth")] 
      public string Orth { get; set; } 

      [JsonProperty(PropertyName = "label")] 
      public string Label { get; set; } 

     } 

    } 
} 
+0

.NET Coreでは、アクションメソッドのmodelパラメーターの前に[FromBody]属性を追加して、Ajaxポストをバインドする必要があります。 ... DocumentUpdateAjax([FromBody] TrainingModelモデル) – Orhun

答えて

0

[FromBody]属性は、ASP.NETコアフレームワークにシリアライザを使用してモデルにリクエストボディのデータをバインドする手がかりを与えます。デフォルトでは、フレームワークはフォームフィールドをバインドします。コントローラメソッドを

に変更してください。
[HttpPost] 
public IActionResult DocumentUpdateAjax([FromBody] TrainingModel model) 
{ 
    .... 
} 
+0

上記の変更により、次の結果が得られます。POST http:// localhost:50991/Tweet/DocumentUpdateAjax 415(サポートされていないメディアタイプ)これは以下の理由によるものと思われます:Content-Type:application/x -www-form-urlencoded; charset = UTF-8。これは何でしょうか? – adam

+0

投稿のContent-Typeはapplication/jsonでなければなりません。あなたの$ .ajax呼び出しで "application/json"が設定されていても、データはフォームのように送信されます。 FromBodyがモデルバインディングをコンフィグレーション済みのシリアライザに委譲するため(JSONはデフォルトで有効)、ASP.NET Core MVCは415で呼び出しを拒否します。適切なシリアライザが見つからない場合(この場合のように)、415が返されます。だから問題は今、理由を見つけることです、なぜjsonは投稿されていません。 –

0

通常のPOSTでデータを送信している可能性があります。 Ajaxのobjextに「json」に

$('#buttonId').on('click', function(e){ 
    e.preventDefault(); 
    // and all of your ajax and js codes... 
}); 

そして dataType属性の値を変更する「 html」:次のようにすべてのコードをラップするようにしてください。

関連する問題