将数据从Ajax帖子绑定到传递给控制器​​

时间:2017-07-21 15:25:12

标签: c# jquery ajax asp.net-core-mvc

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

的Ajax

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

        }

    }
}

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

也许您正在使用普通POST发送数据。尝试包装所有代码:

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

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