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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With