[英]MVC4 passing all form data (model) from javascript to controller — is it possible?
The reply at 的回覆
MVC3 Pass Model view to controller using javascript MVC3使用JavaScript将模型视图传递给控制器
implies that this was impossible, at least for MVC 3. 这意味着这是不可能的,至少对于MVC 3而言是不可能的。
I was wondering if there is any way in MVC 4 to quickly pass the entire form contents (represented by the model) from the .cshtml (razor) view to the controller in JavaScript. 我想知道MVC 4中是否有任何方法可以将整个表单内容(由模型表示)从.cshtml(剃刀)视图快速传递到JavaScript中的控制器。
For example, if I select a dropdown, I may want to return all fields from a form to the controller which will take appropriate action. 例如,如果我选择一个下拉菜单,我可能想将表单中的所有字段返回给控制器,这将采取适当的措施。
Obviously, for large forms it is undesirable to have to do this element-by-element 显然,对于大型表单,不希望必须逐个元素地进行此操作
Basically, you can do it calling an AJAX POST: 基本上,您可以通过调用AJAX POST来做到这一点:
JS (using jQuery): 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
});
});
Controller Action: 控制器动作:
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 UPDATE
For more complex objects, you can use a third part solution for serialization/deserialization. 对于更复杂的对象,可以使用第三方解决方案进行序列化/反序列化。 It's well documented and broaden used:
有充分的文档证明并广泛使用:
Json.NET : http://json.codeplex.com/ Json.NET: http://json.codeplex.com/
Yes it is possible in a simpler way. 是的,有可能以更简单的方式。
Alternate of example provided by MelanciUK. 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) { }
You can achieve the same thing by stadard MVC(ModelBinding) convention ie no need to serialize and deserialize. 您可以通过标准MVC(ModelBinding)约定实现相同的功能,即无需序列化和反序列化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.