Jos*_*gie 2 javascript asp.net-mvc razor asp.net-mvc-3 asp.net-mvc-4
答复在
使用javascript将MVC3 Pass Model视图发送到控制器
意味着这是不可能的,至少对于MVC 3而言.
我想知道MVC 4中是否有任何方法可以将.cshtml(razor)视图中的整个表单内容(由模型表示)快速传递给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
});
});
Run Code Online (Sandbox Code Playgroud)
控制器动作:
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
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
对于更复杂的对象,可以使用第三方解决方案进行序列化/反序列化.它有很好的文档和扩展使用:
Json.NET:http://json.codeplex.com/