JQuery Post Form in ASP.NET MVC 3.0 FormCollection

2019-05-26 04:50发布

问题:

I try to submit a form in Jquery to an Action method in a Controller. To do so I serialize my form and use the get method. In the controller I receive my form as a string like param1=1&param2=2.... Is there a way to retrieve directly a FormCollection in my Action Method instead of the string. As my form has many checkboxes it will be easier for me to have it in formCollection.

Here is my 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");
                    });

Here my form:

@using (Html.BeginForm("CheckSelection", "Check", FormMethod.Post, new { id = "CheckForm" }))
{        
<fieldset>
<div class="editor-label">
    @Html.CheckBox("CodeExist",true)
    @Html.Label("Check Code Existence")
</div>
<div class="editor-label">
    @Html.CheckBox("Mandatory",true)
    @Html.Label("Check Code Reccurence")
</div>
<div class="editor-label">
    @Html.CheckBox("Reccurence",true)
    @Html.Label("Check Mandatory Code")
</div>
}

Here is my Action Method:

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

Thanks in advance for your help!

回答1:

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

and the controller will look like

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

for details of the FormCollection class follow this link



回答2:

So, serializing the form works great for passing all of the form values to the action result, but it then becomes a pain to work with the serialized URL string, especially when I was already using the name/value combination of the FormCollection already. I just wanted to switch the function over to be posted through jQuery instead of a normal form submit. To that end, I wrote a helper function that converts that serialized form into a normal form collection, just as if the form was submitted normally.

Enjoy.

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<string, string> items = new Dictionary<string, string>();      
  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;
}


回答3:

I modified the method provided by @Aaron McCoy above to handle '&' in input:

private FormCollection DeSerialize(string val)
{
FormCollection collection = new FormCollection();
//un-encode, and add spaces back in
var split = val.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
Dictionary<string, string> items = new Dictionary<string, string>();
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;
}

Hope that helps!