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 =开发者_JS百科 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
is not used in the method. What is its purpose?
One of the major advancements of MVC is getting rid of this left - right boring assignment code. It has mechanisms in place that can do this work for you. In this case, you could 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.
Just to make a few comments,
dinner.EventDate = DateTime.Parse(Request.Form["EventDate"]);
is what model binding is supposed to get rid of. Using a strongly typed view, you should get a DateTime type back into dinner.EventDate, without having to do that assigning yourself.The FormCollection returns all the inputs that were submitted via the html form and you are able to retrieve those elements by using the following syntax
formCollection["Title"]
given that the input element's name is "Title"
Strongly typed views are just amazing!
Look at how FormCollection is used here: How can a formcollection be enumerated in ASP.NET MVC?
精彩评论