简体   繁体   English

asp.net mvc formcollection

[英]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. formValues未在方法中使用。 What is its purpose? 它的目的是什么?

One of the major advancements of MVC is getting rid of this left - right boring assignment code. MVC的一个主要进步是摆脱这种左右无聊的赋值代码。 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. 使用强类型视图,您应该将DateTime类型返回到dinner.EventDate中,而不必自行分配。

  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" FormCollection返回通过html表单提交的所有输入,并且您可以使用以下语法formCollection["Title"]检索这些元素, formCollection["Title"]是输入元素的名称是“Title”

Strongly typed views are just amazing! 强烈的类型视图真是太棒了!

看看FormCollection 如何在这里使用: 如何在ASP.NET MVC中枚举formcollection?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM