开发者

asp.net mvc formcollection

开发者 https://www.devze.com 2022-12-30 07:30 出处:网络
publicActionResult Edit(intid, FormCollection formValues) { // Retrieve existing dinner Dinner dinner = dinnerRepository.GetDinner(id);
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,

  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!


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

0

精彩评论

暂无评论...
验证码 换一张
取 消