inforakesha

A fine WordPress.com site

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

Leave a comment

20MAR

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:

1
2
3
4
public ActionResult SubmitFormWithFormCollection()
{
    return View();
}
1
2
3
4
5
6
7
8
9
10
[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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@{
    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:

1
2
3
4
5
6
7
[HttpPost]
public ActionResult SubmitFormWithFormCollection(FormCollection formCollection)
{
    ViewData["firstname"] = formCollection["fistname"];
    return View();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s