繁体   English   中英

MVC4将所有表格数据(模型)从javascript传递到控制器-可能吗?

[英]MVC4 passing all form data (model) from javascript to controller — is it possible?

的回覆

MVC3使用JavaScript将模型视图传递给控制器

这意味着这是不可能的,至少对于MVC 3而言是不可能的。

我想知道MVC 4中是否有任何方法可以将整个表单内容(由模型表示)从.cshtml(剃刀)视图快速传递到JavaScript中的控制器。

例如,如果我选择一个下拉菜单,我可能想将表单中的所有字段返回给控制器,这将采取适当的措施。

显然,对于大型表单,不希望必须逐个元素地进行此操作

基本上,您可以通过调用AJAX POST来做到这一点:

JS(使用jQuery):

$('form').on('submit', function (event) {
    // Stop the default submission
    event.preventDefault();

    // Serialize (JSON) the form's contents and post it to your action
    $.post('YourAction', $(this).serialize(), function (data) {
        // If you want to do something after the post
    });
});

控制器动作:

public ActionResult YourAction(string JSONmodel)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

    MyModel model = serializer.Deserialize(JSONmodel, typeof(MyModel));

    // Now you can do whatever you want with your model
}

UPDATE

对于更复杂的对象,可以使用第三方解决方案进行序列化/反序列化。 有充分的文档证明并广泛使用:

Json.NET: http://json.codeplex.com/

是的,有可能以更简单的方式。

  1. MelanciUK提供的示例的替代方案。

     $('form').on('submit', function (event) { // Stop the default submission event.preventDefault(); // User same property name as in Model $.post('YourAction', {prop1 : 'a', prop2 : 'b'}, function (data) { // If you want to do something after the post }); 

    });

     [HttpPost] public ActionResult SampleAction(SampleModel sModel) { } 

您可以通过标准MVC(ModelBinding)约定实现相同的功能,即无需序列化和反序列化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM