如何使用ajax调用将formcollection传递给action?
我正在尝试用ajax调用替换表单提交。 动作需要formcollection,我不想创建一个新模型。 所以我需要传递整个表单(就像表单提交)但通过ajax调用。 我试图序列化并使用Json,但formcollection是空的。 这是我的行动签名:
public ActionResult CompleteRegisteration(FormCollection formCollection)
这是我的提交按钮点击:
var form = $("#onlineform").serialize(); $.ajax({ url: "/Register/CompleteRegisteration", datatype: 'json', data: JSON.stringify(form), contentType: "application/json; charset=utf-8", success: function (data) { if (data.result == "Error") { alert(data.message); } } });
现在我如何将数据传递给formcollection?
由于FormCollection
是一些键值对,因此JSON的表示forms是不合适的数据格式。 您应该使用序列化的表单字符串:
var form = $("#onlineform").serialize(); $.ajax({ type: 'POST', url: "/Register/CompleteRegisteration", data: form, dataType: 'json', success: function (data) { if (data.result == "Error") { alert(data.message); } } });
主要变化:
- 设置为POST的请求类型 (此处不需要,但看起来更自然)
- 序列化表单而不是JSON字符串作为请求数据
- 删除了contentType – 我们不再发送JSON了
尝试:
$().on('submit',function(){ $.ajax({ url: "/Register/CompleteRegisteration" + $(this).serialize(), // place the serialized inputs in the ajax call datatype: 'json', contentType: "application/json; charset=utf-8", success: function (data) { if (data.result == "Error") { alert(data.message); } } }); });
如果有人想要向FormCollection添加其他数据,那么您可以尝试下面。
行动方法
public ActionResult GetUser(FormCollection frm) { int UserId = Convert.ToInt32(frm["user"]); // your code return Json(data, JsonRequestBehavior.AllowGet); }
有关详细信息,请参阅链接 http://geekswithblogs.net/rgupta/archive/2014/06/25/combining-jquery-form-serialize-and-json.stringify-when-doing-ajax-post.aspx