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.
[…] using FormCollection is a better way to get values from View to Controller than this post, I’d say the better […]
[…] With System.Web.Mvc.FormCollection […]
i want to know how can i get values of the html form in asp.net
Thanks, helped clear a lot up
It really helped me. Thanks
It really helped me tooo 🙂
somthing good))
simple and effective
Thank’s
thanks, worked well.
Thanks, it works.
It worked for me also..nice article..
Hi, This is one is good and work also. Thanks for that. but I want to pass one form value to another form.
nice article