javascript - ASP.NET MVC Controller 接受 javascript 对象

标签 javascript asp.net-mvc

从 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 传递信息,您需要提供两个参数:dataTypecontentType。 (我想 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/

相关文章:

javascript - 使用 jQuery 更改一个元素的 CSS 不起作用

javascript - 如何捕获和解析从 Google Maps v3 API 返回的 JSON?

c# - 模型数据未传递给 Asp Mvc 中的 View

javascript - JWPlayer 意外 token 非法

javascript - 拒绝执行来自 p.adsymptotic.com 的脚本

asp.net-mvc - 需要日期时间(+18 年)

asp.net-mvc - 使用 MSpec 测试 ActionFilterAttributes

asp.net-mvc - ASP.NET MVC 多对多关系,使用 "My Own"表

c# - 查看模型结果的下拉列表

javascript - 使用 javascript 或 jquery 将所有代码放在一个 div 类中