maztt
maztt

Reputation: 12294

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 is not used in the method. What is its purpose?

Upvotes: 7

Views: 31528

Answers (3)

Pieter Germishuys
Pieter Germishuys

Reputation: 4886

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!

Upvotes: 1

Malevolence
Malevolence

Reputation: 1857

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.

Upvotes: 24

Daniel Dyson
Daniel Dyson

Reputation: 13230

Look at how FormCollection is used here: How can a formcollection be enumerated in ASP.NET MVC?

Upvotes: 0

Related Questions