当我使用文字字符串化的JSON对象时,所有工作都按预期工作
Index.cshtml(使用文字ajax字符串$ .ajax WORKS)
var searchObject = new Object();
searchObject.Thing1 = '42';
searchObject.Thing2 = '43';
searchObject.Thing3 = '44';
var searchSerialized = JSON.stringify(searchObject);
alert(searchSerialized);
$.ajax(
{
url: '/api/auditApi',
type: "Post",
contentType: "application/json; charset=utf-8",
data: '{\'Thing1\':\'42\',\'Thing2\':\'43\',\'Thing3\':\'44\'}',
dataType: 'json',
success: function (result) {
$(".kendoAudit").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
$(".kendoAudit").data("kendoGrid").dataSource.read();
$(".kendoAudit").data("kendoGrid").refresh();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
}
});
但是,当我使用内联创建的序列化对象时,它会将null传入post post
Index.cshtml(对象创建为内联并传递给$ .ajax FAILS)
var searchObject = new Object();
searchObject.Thing1 = '42';
searchObject.Thing2 = '43';
searchObject.Thing3 = '44';
var searchSerialized = JSON.stringify(searchObject);
alert(searchSerialized);
$.ajax(
{
url: '/api/auditApi',
type: "Post",
contentType: "application/json; charset=utf-8",
data: searchSerialized, //I have tried concatenating with + '' also
dataType: 'json',
success: function (result) {
$(".kendoAudit").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
$(".kendoAudit").data("kendoGrid").dataSource.read();
$(".kendoAudit").data("kendoGrid").refresh();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
}
});
控制器
public HttpResponseMessage Post([FromBody]string value)
{
try
{
var results = JsonConvert.DeserializeObject<dynamic>(value);
}
catch (Exception ex)
{
// throws because value is null.
}
}
我确信在转换过程中我遗漏了很多东西。
调试行:alert(searchSerialized);
显示我期待的内容
答案 0 :(得分:0)
您可以直接将数据输入模型。 当发布序列化对象(不再是字符串)时,MVC会自动将其绑定到正确的模型。
现在改变你的行动方法。
public class SearchObject
{
public int Thing1 { get; set; }
public int Thing2 { get; set; }
public int Thing3 { get; set; }
}
[HttpPost]
public ActionResult Test(SearchObject searchObject)
{
return View();
}