2017-07-21 56 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中,您必須在action方法的模型參數之前添加[FromBody]屬性來綁定Ajax帖子。 ... DocumentUpdateAjax([FromBody] TrainingModel model) – Orhun

回答

0

[FromBody]屬性給出ASP.NET核心框架通過使用串行化器對所述請求的身體模型的數據綁定的線索。默認情況下,框架綁定表單域。嘗試將控制器方法更改爲

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

上述更改導致:POST http:// localhost:50991/Tweet/DocumentUpdateAjax 415(Unsupported Media Type)我會認爲這是因爲:Content-Type:application/x -www窗體-urlencoded;字符集= UTF-8。這應該是什麼? – adam

+0

帖子的內容類型必須是application/json。不知何故,您的數據像表單一樣提交;儘管您的$ .ajax調用已設置「application/json」。 ASP.NET Core MVC拒絕使用415調用,因爲FromBody將模型綁定委託給配置的序列化器(默認啓用JSON);如果找不到合適的串行器(如這種情況),則返回415。所以現在的問題是找到原因,爲什麼沒有發佈json。 –

0

也許您正在使用普通POST發送數據。嘗試包所有的代碼是這樣的:

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

而在阿賈克斯objext改變dataType屬性的值「html」到「json」。

相關問題