asp.net-mvc ASP.NET MVC UpdateModel() 方法如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1087279/
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-07 23:42:28  来源:igfitidea点击:

How does the ASP.NET MVC UpdateModel() method work?

asp.net-mvc

提问by Kirschstein

I'm working on my first .NET MVC application and using the NerdDinner tutorial as a reference point. One point that is intriguing me at the moment is the UpdateModel()method. (I don't like using things I don't really understand.)

我正在开发我的第一个 .NET MVC 应用程序并使用 NerdDinner 教程作为参考点。目前让我感兴趣的一点是UpdateModel()方法。(我不喜欢使用我不太了解的东西。)

Taken from the NerdDinner tutorial-

取自NerdDinner 教程-

//
// POST: /Dinners/Edit/2

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues) {

    Dinner dinner = dinnerRepository.GetDinner(id);

    UpdateModel(dinner);

    dinnerRepository.Save();

    return RedirectToAction("Details", new { id = dinner.DinnerID });
}

My main question is how does the UpdateModel()get access to the formValues passed in the Edit method? Why is the collection not passed in explicitly as a parameter to the method?

我的主要问题是如何UpdateModel()访问 Edit 方法中传递的 formValues?为什么集合没有作为参数显式传递给方法?

回答by Jordan

UpdateModel() is a Controller helper method that attempts to bind a bunch of different input data sources (HTTP POST data coming from a View, QueryString values, Session variables/Cookies, etc.) to the explicit model object you indicate as a parameter. Essentially, it is only for model binding.

UpdateModel() 是一个 Controller 辅助方法,它尝试将一堆不同的输入数据源(来自视图的 HTTP POST 数据、QueryString 值、会话变量/Cookie 等)绑定到您指定为参数的显式模型对象。本质上,它仅用于模型绑定。

If you express the input parameters for your Action as a strongly-typed model (like a View Model), you've already taken all of the steps that are done behind the scenes when UpdateModel() is called. If you retrieve an object from the DataContext and edit its properties, SaveChanges() is all you need to push the updates back to the database (in this case, Save()).

如果您将 Action 的输入参数表示为强类型模型(如视图模型),则您已经执行了调用 UpdateModel() 时在幕后完成的所有步骤。如果您从 DataContext 检索对象并编辑其属性,则只需使用 SaveChanges() 将更新推送回数据库(在本例中为 Save())。

Example:

例子:

//
// POST: /Dinners/Edit/2

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(DinnerViewModel incoming) {

    var dinner = dinnerRepository.GetDinner(incoming.DinnerID);
    dinner.Description = incoming.Description;
    dinnerRepository.Save();

    return RedirectToAction("Details", new { id = incoming.DinnerID });
}

However,there is a use-case for using UpdateModel() with a strongly-typed model: when you are passing in a strongly-typed model and want its values to directly replace those of an entity from the database (provided they are all named and typed the same). In this case, you would retrieve the object, use UpdateModel() on it, and its model binding operation will pull in any similarly-named and typed properties from the strongly-typed object to the retrieved object. In other words, it will perform reflectionfor you.

但是,有一个用例可以将 UpdateModel() 与强类型模型一起使用:当您传入强类型模型并希望其值直接替换数据库中实体的值时(前提是它们都已命名)并输入相同的内容)。在这种情况下,您将检索该对象,对其使用 UpdateModel(),它的模型绑定操作会将任何名称和类型相似的属性从强类型对象拉入到检索到的对象中。换句话说,它会为你进行反思

So, like your example, if you want all properties to update without specifying which to update, and your strongly-typed model and database model have similarly-named properties, you would still want to use UpdateModel() to take advantage of the reflection.

因此,就像您的示例一样,如果您希望在不指定要更新的情况下更新所有属性,并且您的强类型模型和数据库模型具有类似命名的属性,您仍然希望使用 UpdateModel() 来利用反射。

Example:

例子:

//
// POST: /Dinners/Edit/2

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(DinnerViewModel incoming) {

    var dinner = dinnerRepository.GetDinner(incoming.DinnerID);
    UpdateModel(dinner);
    dinnerRepository.Save();

    return RedirectToAction("Details", new { id = incoming.DinnerID });
}

The only advantage here (over using a FormCollection object) is that you'd have access to all other properties of the strongly-typed object (as shown by incoming.DinnerID).

这里的唯一优势(相对于使用 FormCollection 对象)是您可以访问强类型对象的所有其他属性(如incoming.DinnerID 所示)。

Conclusion: if you're translating a strongly-typed object to a derived object, it's probably easiest to use UpdateModel(). However, it's largely unnecessary if you are simply updating a few properties of the derived object. Also, be aware that use of the Entity Framework (instead of something like Linq to SQL) makes all of this moot, as it can relate strongly-typed objects and derived objects with its own methods.

结论:如果您要将强类型对象转换为派生对象,那么使用 UpdateModel() 可能是最简单的。但是,如果您只是更新派生对象的一些属性,则在很大程度上是不必要的。此外,请注意使用实体框架(而不是像 Linq to SQL 这样的东西)使所有这些都没有实际意义,因为它可以将强类型对象和派生对象与其自己的方法联系起来。

回答by Andrei R?nea

It does inspect all the HttpRequest inputs such as Form, QueryString, Cookies and Server variables. I think in this order.

它会检查所有 HttpRequest 输入,例如 Form、QueryString、Cookies 和 Server 变量。我想按这个顺序。

回答by Rahul Mahajan

Instead of passing Model object as a parameter to "Post()" action method, we are creating an instance of an Model object within the "Post()" function, and updating it using "UpdateModel()" function. "UpdateModel()" function inspects all the HttpRequest inputs such as posted Form data, QueryString, Cookies and Server variables and populate the employee object.

我们没有将 Model 对象作为参数传递给“Post()”操作方法,而是在“Post()”函数中创建一个 Model 对象的实例,并使用“UpdateModel()”函数更新它。“UpdateModel()”函数检查所有 HttpRequest 输入,例如发布的表单数据、QueryString、Cookie 和服务器变量,并填充员工对象。

e.g.

例如

[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
        EmployeeBusinessLayer employeeBusinessLayer =
            new EmployeeBusinessLayer();
        Employee employee = new Employee();
        UpdateModel(employee);
        employeeBusinessLayer.AddEmmployee(employee);
        return RedirectToAction("Index");
}