我需要使用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; }
}
}
}
在.NET Core中,您必須在action方法的模型參數之前添加[FromBody]屬性來綁定Ajax帖子。 ... DocumentUpdateAjax([FromBody] TrainingModel model) – Orhun