ASP.NET MVC表单集合

7
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在该方法中没有被使用,它的目的是什么?


考虑使用ViewModels代替FormCollection http://www.jacopretorius.net/2010/01/use-view-models-instead-of-formcollection.html - Custodio
3个回答

24

MVC的一个重要进展是消除这种左右繁琐的赋值代码。它具有可以为您完成此工作的机制。在这种情况下,您可以执行以下操作:

Dinner dinner = dinnerRepository.GetDinner(id);
UpdateModel(dinner, formValues); // Automatically updates properties with values from the collection
dinnerRepository.Save();
希望这可以帮助到你。

我能否从模型属性中创建或添加键值对到formcollection中?可以使用Add方法。 - Shaiju T

1

只是想发表一些评论:

  1. dinner.EventDate = DateTime.Parse(Request.Form["EventDate"]); 这段代码本应该被模型绑定所替代。 使用强类型视图,您应该能够将 DateTime 类型直接赋值给 dinner.EventDate,而无需手动进行赋值。

  2. FormCollection 返回通过 HTML 表单提交的所有输入,您可以使用以下语法检索这些元素:formCollection["Title"],假设输入元素的名称为 "Title"。

强类型视图真是太棒了!


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接