Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc formcollection

Tags:

asp.net-mvc

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?

like image 858
maztt Avatar asked May 13 '10 08:05

maztt


2 Answers

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.

like image 96
Malevolence Avatar answered Oct 30 '22 23:10

Malevolence


Just to make a few comments,

  1. 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.

  2. 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!

like image 36
Pieter Germishuys Avatar answered Oct 31 '22 01:10

Pieter Germishuys