2017-07-21 27 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”。

相关问题