asp.net-mvc asp.net mvc 表单集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2825352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:18:15  来源:igfitidea点击:

asp.net mvc formcollection

asp.net-mvc

提问by maztt

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 });
}

formValuesis not used in the method. What is its purpose?

formValues方法中不使用。它的目的是什么?

采纳答案by Daniel Dyson

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

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

回答by Malevolence

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:

MVC 的主要进步之一是摆脱了这种左右无聊的赋值代码。它具有可以为您完成这项工作的机制。在这种情况下,您可以执行以下操作:

Dinner dinner = dinnerRepository.GetDinner(id);
UpdateModel(dinner, formValues); // Automatically updates properties with values from the collection
dinnerRepository.Save();

Hope this helps.

希望这可以帮助。

回答by Pieter Germishuys

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"

  1. dinner.EventDate = DateTime.Parse(Request.Form["EventDate"]);是模型绑定应该摆脱的。使用强类型视图,您应该将 DateTime 类型返回到 Dinner.EventDate 中,而不必自己进行分配。

  2. FormCollection 返回通过 html 表单提交的所有输入,并且您可以使用以下语法检索这些元素 formCollection["Title"],因为输入元素的名称是“Title”

Strongly typed views are just amazing!

强类型视图真是太棒了!