jquery – 将json提交给MVC3动作

前端之家收集整理的这篇文章主要介绍了jquery – 将json提交给MVC3动作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个用Knockout.js创建的表单.当用户按下提交按钮时,我将视图模型转换回模型并尝试提交给服务器.我试过了:
  1. ko.utils.postJson(location.href,ko.toJSON(viewmodel));

但是当它撞到服务器时,该对象是空白的.我切换到这段代码

  1. $.ajax({
  2. url: location.href,type: "POST",data: ko.toJSON(viewmodel),datatype: "json",contentType: "application/json charset=utf-8",success: function (data) { alert("success"); },error: function (data) { alert("error"); }
  3. });

这会将数据传输到服务器,并在其中包含正确的数据.

但我想要的是提交数据,以便我的控制器可以重定向到正确的视图.有什么建议么?

解决方法

Steve Sanderson有一个较旧的示例,它演示了如何在控制器操作中正确绑定提交的JSON数据: http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/

它的要点是他创建了一个名为“FromJson”的属性,如下所示:

  1. public class FromJsonAttribute : CustomModelBinderAttribute
  2. {
  3. private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();
  4.  
  5. public override IModelBinder GetBinder()
  6. {
  7. return new JsonModelBinder();
  8. }
  9.  
  10. private class JsonModelBinder : IModelBinder
  11. {
  12. public object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
  13. {
  14. var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
  15. if (string.IsNullOrEmpty(stringified))
  16. return null;
  17. return serializer.Deserialize(stringified,bindingContext.ModelType);
  18. }
  19. }
  20. }

然后,动作看起来像:

  1. [HttpPost]
  2. public ActionResult Index([FromJson] IEnumerable<GiftModel> gifts)

现在,您可以使用ko.utils.postJson提交数据并使用适当的视图进行响应.

猜你在找的jQuery相关文章