从 chrome 开发人员工具中,我看到我的请求正在将此信息发送到我的 Controller :
models:[{"Id":null,"Start":"2014-06-11T12:17:52.452Z","End":"2014-06-11T12:17:52.452Z","Name":"test","Status":"test"}]
如何在我的 MVC Controller 中接受它?
它看起来像是一个只有一个元素的 javascript 数组。
在服务器端我有方法接受:Foo(Bar models)
也试过Foo(List<Bar> models)
模型值始终为 null
.有什么建议,如何为我的服务器获取值(value)?
最佳答案
因此,要使用 AJAX 传递信息,您需要提供两个参数:dataType
和 contentType
。 (我想 dataType
是可选的,但如果您希望返回 JSON,最好提供它。)。然而,contentType
让 MVC [ModelBinder
] 知道传入的请求不仅仅是一个字符串,而是一个需要反序列化回对象的对象。
话虽如此,以下内容应该适合您的情况:
// This is your to-be-sent data'
// However you collect it, but for now we're storing it as a plain object.
var jso = { models: [{ "Id": null, "Start": "2014-06-11T12:17:52.452Z", "End": "2014-06-11T12:17:52.452Z", "Name": "test", "Status": "test" }] }
// Here we turn it into JSON
var json = JSON.stringify(jso);
// And now we send it off to the controller/action:
$.ajax({
url: '@Url.Action("SomeAction","SomeController")',
type: 'POST',
data: json, // pass of data serialized
dataType: 'json', // expecting json back
contentType: 'application/json; charset=utf-8', // hey ModelBinder, deserialize this!
})/* handle the Deferred callbacks (.done, .fail, .always) */;
然后,在你的 Controller 中:
public class SomeController : Controller
{
[HttpPost]
public JsonResult SomeAction(IList<MyModel> models)
{
// Should pass now
if (ModelState.IsValid)
{
// Handle it and return back the response
// Given the above, you have something like the following now
// assigned to "models":
// models = new List<MyModel> {
// new MyModel {
// Id = null,
// Start = new DateTime(2014, 11, 6, 12, 17, 52),
// End = new DateTime(2014, 11, 6, 12, 17, 52),
// Name = "test",
// Status = "test"
// }
// };
return Json(new {Models = models }); // just to see it come back
}
return Json(new { Error = true, Message = "Invalid model" });
}
}
可以看到工作示例On GitHub顺便说一下。
关于javascript - ASP.NET MVC Controller 接受 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24162865/