C# 将数据从Ajax post绑定到传递给控制器的模型

C# 将数据从Ajax post绑定到传递给控制器的模型,c#,jquery,ajax,asp.net-core-mvc,C#,Jquery,Ajax,Asp.net Core Mvc,我需要使用Ajax调用更新文档,但是我没有成功地将Ajax调用中的数据绑定到传递给控制器的模型 我做错了什么 我还尝试将控制器的定义更改为使用字符串,这避免了下面的NullReferenceException,但字符串是作为null传递的 请求有效负载 {"model":{"Text":"Test","LastUpdated":null,"TrainingSentiment":"Test","Sentiment":"Test","SentimentScore":"-1","Entities":[

我需要使用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()
控制器

[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; }

        }

    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Http;
使用Newtonsoft.Json;
命名空间TextualAnalytics.Models
{
公共类培训模型:Microsoft.Azure.Documents.Document
{
[JsonProperty(PropertyName=“text”)]
公共字符串文本{get;set;}
[JsonProperty(PropertyName=“上次更新”)]
公共日期时间?上次更新的{get;set;}
[JsonProperty(PropertyName=“training_”)]
公共字符串训练设置{get;set;}
[JsonProperty(PropertyName=“情绪”)]
公共字符串{get;set;}
[JsonProperty(PropertyName=“情绪分数”)]
公共字符串{get;set;}
[JsonProperty(PropertyName=“entities”)]
公共列表实体{get;set;}
公共类实体
{
[JsonProperty(PropertyName=“start”)]
公共长启动{get;set;}
[JsonProperty(PropertyName=“end”)]
公共长端{get;set;}
[JsonProperty(PropertyName=“value”)]
公共字符串值{get;set;}
[JsonProperty(PropertyName=“orth”)]
公共字符串ORH{get;set;}
[JsonProperty(PropertyName=“label”)]
公共字符串标签{get;set;}
}
}
}

属性为ASP.NET核心框架提供了使用序列化程序将请求主体的数据绑定到模型的线索。默认情况下,框架绑定表单字段。尝试将控制器方法更改为

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

[FromBody]
属性为ASP.NET核心框架提供了使用序列化程序将请求主体的数据绑定到模型的线索。默认情况下,框架绑定表单字段。尝试将控制器方法更改为

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

也许你是用普通邮件发送数据。请尝试按以下方式包装所有代码:

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

并将ajaxobjext中的
dataType
属性的值“
html
”更改为“
json
”。

可能您正在使用普通POST发送数据。请尝试按以下方式包装所有代码:

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

并将ajax对象文本中的
dataType
属性的值“
html
”更改为“
json
”。

在.NET Core中,必须在操作方法的模型参数之前添加[FromBody]属性以绑定ajax post。。。DocumentUpdateAjax([FromBody]TrainingModel model)在.NET Core中,必须在操作方法的模型参数之前添加[FromBody]属性以绑定Ajax post。。。DocumentUpdateAjax([FromBody]TrainingModel model)上述更改导致:POST 415(不支持的媒体类型),我认为这是因为:内容类型:application/x-www-form-urlencoded;字符集=UTF-8。这应该是什么?帖子的内容类型必须是application/json。不知何故,您的数据会像表单一样提交;尽管$.ajax调用设置了“application/json”。ASP.NET Core MVC使用415拒绝调用,因为FromBody将模型绑定委托给配置的序列化程序(默认情况下启用JSON);如果没有找到合适的序列化程序(如本例),则返回415。因此,现在的问题是找到原因,为什么没有发布json;字符集=UTF-8。这应该是什么?帖子的内容类型必须是application/json。不知何故,您的数据会像表单一样提交;尽管$.ajax调用设置了“application/json”。ASP.NET Core MVC使用415拒绝调用,因为FromBody将模型绑定委托给配置的序列化程序(默认情况下启用JSON);如果没有找到合适的序列化程序(如本例),则返回415。所以现在的问题是找到原因,为什么没有发布json。