ASP.NET MVC 3.0 FormCollection中的JQuery Post表单

我尝试将Jquery中的表单提交给Controller中的Action方法。 为此,我序列化我的表单并使用get方法。 在控制器中,我收到我的表单作为字符串,如param1 = 1&param2 = 2 ….有没有办法直接检索我的Action方法中的FormCollection而不是字符串。 由于我的表单有很多复选框,因此我更容易在formCollection中使用它。

这是我的Jquery:

var form = $("#CheckForm"); var formCollection = form.serialize(); $.post('@Url.Action("CheckSelection")', { clientId: clientId, policyId: policyId, countryCode: country, month: monthtoken[0] + '*' + monthtoken[1], formCollection: formCollection }, function () { alert("formSubmit"); }); 

我的表格在这里:

 @using (Html.BeginForm("CheckSelection", "Check", FormMethod.Post, new { id = "CheckForm" })) { 
@Html.CheckBox("CodeExist",true) @Html.Label("Check Code Existence")
@Html.CheckBox("Mandatory",true) @Html.Label("Check Code Reccurence")
@Html.CheckBox("Reccurence",true) @Html.Label("Check Mandatory Code")
}

这是我的行动方法:

  [AcceptVerbs(HttpVerbs.Post)] public ActionResult CheckSelection(string clientId, string policyId, string countryCode, string month, FormCollection formCollection){} 

在此先感谢您的帮助!

 var form = $("#CheckForm"); var formCollection = form.serialize(); $.post('@Url.Action("CheckSelection")', formCollection , function (data) { alert(data); //will alert form submitted }); 

控制器看起来像

 [AcceptVerbs(HttpVerbs.Post)] public ActionResult CheckSelection(FormCollection collection){ return Content("form submitted"); } 

有关FormCollection类的详细信息,请单击此链接

因此,序列化表单非常适合将所有表单值传递给操作结果,但是使用序列化URL字符串会变得很麻烦,特别是当我已经使用FormCollection的名称/值组合时。 我只是想通过jQuery而不是普通的表单提交来切换function。 为此,我编写了一个帮助函数,将序列化的表单转换为普通的表单集合,就像表单正常提交一样。

请享用。

 private FormCollection DeSerialize(FormCollection form) { FormCollection collection = new FormCollection(); //un-encode, and add spaces back in string querystring = Uri.UnescapeDataString(form[0]).Replace("+", " "); var split = querystring.Split(new [] {'&'}, StringSplitOptions.RemoveEmptyEntries); Dictionary items = new Dictionary(); foreach (string s in split) { string text = s.Substring(0, s.IndexOf("=")); string value = s.Substring(s.IndexOf("=")+1); if (items.Keys.Contains(text)) items[text] = items[text] + "," + value; else items.Add(text, value); } foreach (var i in items) { collection.Add(i.Key, i.Value); } return collection; } 

我修改了@Aaron McCoy上面提供的方法来处理输入中的’&’:

 private FormCollection DeSerialize(string val) { FormCollection collection = new FormCollection(); //un-encode, and add spaces back in var split = val.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries); Dictionary items = new Dictionary(); foreach (string s in split) { var v = Uri.UnescapeDataString(s).Replace("+", " "); string text = v.Substring(0, v.IndexOf("=")); string value = v.Substring(v.IndexOf("=") + 1); if (items.Keys.Contains(text)) items[text] = items[text] + "," + value; else items.Add(text, value); } foreach (var i in items) { collection.Add(i.Key, i.Value); } return collection; } 

希望有所帮助!