我正在学习使用 Ajax 进行 POST,我注意到很多在静态数组上使用 stringify 的示例。
在我的示例中,我通过从 <input>
中提取的 jQuery 对象构建数组值(value)观。
查询
function PostEdit(vData){
var content = JSON.stringify(vData); //content = "[{"Id":"1","Date":"7/12/2017 12:00:00 AM"}]"
$.ajax({
url: '@Url.Action("Index", "PostViewData")',
type: "POST",
data: JSON.stringify({ ViewData : vData }),
contentType: "application/json",
success: function (result) {
alert("success" + result);
},
error: function (result) {
alert("failure" + result);
}
});
return;
}
Controller
[HttpPost]
public ActionResult Index(List<DataViewModel> ViewData )
{
if(ViewData != null)
{
var json = new { success = true };
return Json(json);
}
return Json(false);
}
View 模型
public class DataViewModel
{
public DataViewModel(string id, string date)
{
Id = id;
Date = date;
}
public string Id { get; set; }
public string Date { get; set; }
}
在哪里DataViewModel
是一个由两个值组成的类,Id
, 和 Date
对应于我的 JS 对象。
自 vData
将函数作为值 vData = [Object]
输入, 当我调用 .stringify(vData)
它返回 content = "[{"Id":"1","Date":"7/12/2017 12:00:00 AM"}]"
content
的值以上是我看到的大多数示例在 stringify 之前的结构,例如示例 here .
一旦采用这种格式,大多数响应、示例都会调用 stringify。
现在当我调用 .stringify(ViewData : vData)
我什至没有到达 Controller 。 Ajax 无法发布。相反,当我调用 .stringify(ViewData : content)
,我将其发送到 Controller ,但值为空。我错过了什么/误解了什么?
我正在寻找关于 Ajax Post 和 Stringify 的更好解释,以及它如何与 Controller 参数交互。
最佳答案
只需将无参数构造函数添加到您的模型中。通过该更改,您的代码将按原样运行。 ASP 无法将您的 json 解析为 DataViewModel,因为它试图调用不存在的默认构造函数。
public class DataViewModel
{
public DataViewModel()
{
}
//...other methods and members here
}
关于javascript - Ajax POST 和 Stringify 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064377/