Asp.net mvc formcollection

public ActionResult Edit(int id, FormCollection formValues) { // Retrieve existing dinner Dinner dinner = dinnerRepository.GetDinner(id); // Update dinner with form posted values dinner.Title = Request.Form["Title"]; dinner.Description = Request.Form["Description"]; dinner.EventDate = DateTime.Parse(Request.Form["EventDate"]); dinner.Address = Request.Form["Address"]; dinner.Country = Request.Form["Country"]; dinner.ContactPhone = Request.Form["ContactPhone"]; // Persist changes back to database dinnerRepository.Save(); // Perform HTTP redirect to details page for the saved Dinner return RedirectToAction("Details", new { id = dinner.DinnerID }); } 

formValues not used in the method. What is his purpose?

+7
asp.net-mvc
source share
3 answers

See how FormCollection is used here: How can I convert a formcollection to ASP.NET MVC?

0
source share

One of the main achievements of MVC is to get rid of this code from left to right. It has mechanisms that can do this job for you. In this case, you can do something like this:

 Dinner dinner = dinnerRepository.GetDinner(id); UpdateModel(dinner, formValues); // Automatically updates properties with values from the collection dinnerRepository.Save(); 

Hope this helps.

+25
source share

To make a few comments,

  • dinner.EventDate = DateTime.Parse(Request.Form["EventDate"]); - this is what the model binding should get rid of. Using a strongly typed view, you should get the DateTime type back in dinner.EventDate, without requiring this, assigning yourself.

  • FormCollection returns all the inputs that were submitted via the html form, and you can get these elements using the following syntax formCollection["Title"] , given that the name of the input element is "Title"

Strongly typed views are amazing!

+1
source share

All Articles