Get Form’s Post Values in ASP.NET MVC with FormCollection

In addition to this post, you can also get the form’s post values with System.Web.Mvc.FormCollection in ASP.NET MVC 2 or MVC 3.

Here are my controllers, one for display the page, one for process page post back:

public ActionResult SubmitFormWithFormCollection()
{
    return View();
}
[HttpPost]
public ActionResult SubmitFormWithFormCollection(FormCollection formCollection)
{
    foreach (string _formData in formCollection)
    {
        ViewData[_formData] = formCollection[_formData];
    }

    return View();
}

Here’s my code in Razor view engine:

@{
    ViewBag.Title = "Submit Form With FormCollection";
}

<h2>Submit Form with FormCollection</h2>

@using (Html.BeginForm())
{
    <div>
        You have submitted:<br />
        Firstname: @ViewData["firstname"]<br />
        Lastname: @ViewData["lastname"]<br />
        Email: @ViewData["email"]<br />
    </div>
    <br />

    <label for="firstname">Firstname:</label>
    <input type="text" name="firstname" />
    <br />
    <label for="lastname">Lastname:</label>
    <input type="text" name="lastname" />
    <br />
    <label for="email">Email:</label>
    <input type="text" name="email" />
    <br />
    <br />

    <input type="submit" name="submit" />
}

When the view is loaded, it looks like:

And when it posted:

FormCollection (System.Web.Mvc.FormCollection) class contains key / value pairs from all the fields in the form submitted.

The FormCollection’s key is the ‘name’ attribute of the HTML control field in the form while the value is the user’s input to that field. So, to get value of the ‘firstname’ field, I can do:

[HttpPost]
public ActionResult SubmitFormWithFormCollection(FormCollection formCollection)
{
    ViewData["firstname"] = formCollection["fistname"];

    return View();
}

There are many ways to iterate through System.Web.Mvc.FormCollection. See this post for detail.

14 thoughts on “Get Form’s Post Values in ASP.NET MVC with FormCollection”

Leave a comment