简体   繁体   English

何时以及为何在asp.net mvc 2中使用TryUpdateModel?

[英]When and why do you use TryUpdateModel in asp.net mvc 2?

I can't seem to find just a basic code sample to see how TryUpdateModel works? 我似乎无法找到一个基本的代码示例,看看TryUpdateModel是如何工作的? When do you use it and why? 你什么时候使用它,为什么?

You can use this method to update the model that backs a particular view via the given controller. 您可以使用此方法更新通过给定控制器支持特定视图的模型。 For example, if I have a view displaying a Foo object with property Bar populated by a textbox, I can call a method Save() on the controller and call TryUpdateModel to attempt to update the Foo. 例如,如果我有一个显示Foo对象的视图,其中属性栏由文本框填充,我可以在控制器上调用方法Save()并调用TryUpdateModel来尝试更新Foo。

public class Foo {
  public string Bar { get; set; }
}

// ... in the controller
public ActionResult Save() {
  var myFoo = new Foo();
  TryUpdateModel(myFoo);
}

This will try to update the model with the given value for Bar. 这将尝试使用Bar的给定值更新模型。 If the update fails validation (say, for example, that Bar was an integer and the textbox had the text "hello" in it) then TryUpdateModel will pass update the ViewData ModelState with validation errors and your view will display the validation errors. 如果更新未通过验证(例如,Bar是一个整数且文本框中包含文本“hello”),则TryUpdateModel将通过更新ViewData ModelState并显示验证错误,您的视图将显示验证错误。

Make sure you pay close attention to the security warning for .NET Framework 4 in the MSDN documentation: 确保在MSDN文档中密切关注.NET Framework 4的安全警告:

Security Note Use one of the [Overload:System.Web.Mvc.Controller.TryUpdateModel``1] methods that takes either a list of properties to include (a whitelist) or a list of properties to exclude (a blacklist). 安全说明使用[Overload:System.Web.Mvc.Controller.TryUpdateModel``1]方法之一,该方法包含要包括的属性列表(白名单)或要排除的属性列表(黑名单)。 If no explicit whitelist or blacklist is passed, the [Overload:System.Web.Mvc.Controller.TryUpdateModel`1] method tries to update every public property in the model for which there is a corresponding value in the request. 如果未传递明确的白名单或黑名单,则[Overload:System.Web.Mvc.Controller.TryUpdateModel`1]方法会尝试更新模型中的每个公共属性,其中请求中存在相应的值。 A malicious user could exploit this in order to update properties that you do not intend to provide access to. 恶意用户可以利用此功能来更新您不打算提供访问权限的属性。

https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.100).aspx https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.100).aspx

TryUpdateModel() allows you to bind parameters to your model inside your action. TryUpdateModel()允许您将参数绑定到操作中的模型。 This is useful if you want to load your model from a database then update it based on user input rather than taking the entire model from user input. 如果要从数据库加载模型然后根据用户输入更新模型而不是从用户输入中获取整个模型,这将非常有用。

public ActionResult Update(int id) {
    var service = new ServiceClass();
    var record = service.LoadModel(id);
    if (!TryUpdateModel(record)) {
        // There was an error binding data
        return View();
    }
    // Everything was ok, now save the record back to the database
    service.SaveModel(record);
    return View("Success");
}

It acts similar to UpdateModel() in this respect but returns true on success and false if there is an error. 它在这方面的行为类似于UpdateModel() ,但在成功时返回true,如果有错误则返回false。 UpdateModel() throws an exception if there is an error which requires a bit more code. 如果存在需要更多代码的错误, UpdateModel()会抛出异常。

Note: You might want to use one of the overloads that allows you to limit which properties can be updated. 注意:您可能希望使用其中一个重载,以允许您限制可以更新的属性。

We also used TryUpdateModel to avoid Model Binding magic before the Action was called; 在调用Action之前,我们还使用了TryUpdateModel来避免模型绑定魔法; instead we took a HttpFormCollection as our parameter and called TryUpdateModel within the method. 相反,我们将HttpFormCollection作为参数,并在方法中调用TryUpdateModel The clean boolean value returned from this allowed control flow to be passed to a Success or Failure method for the Action. 从此允许的控制流返回的clean boolean值将传递给Action的Success或Failure方法。 eg 例如

public ActionResult Save(HttpFormCollection formCollection)
{
  var saveModel = new SaveModel(); // or from a Factory etc
  var validModel = TryUpdateModel(_saveModel, formCollection); // order may be incorrect
  return validModel ? Save(saveModel) : InvalidSaveModel(saveModel);
}

We found it quite easy to build a HttpFormCollection for all our validation cases and therefore test the action. 我们发现为所有验证案例构建HttpFormCollection非常容易,因此测试操作。

暂无
暂无

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

相关问题 TryUpdateModel Asp.Net MVC无法正常工作 - TryUpdateModel Asp.Net MVC is not working ASP.NET MVC中的DropDownListFor和TryUpdateModel - DropDownListFor and TryUpdateModel in ASP.NET MVC ASP.NET MVC 5 TryUpdateModel不允许&在字符串中 - ASP.NET MVC 5 TryUpdateModel not allowing & in string ASP.NET MVC 3-调用UpdateModel或TryUpdateModel时如何有条件地验证(IValidatableObject)? - ASP.NET MVC 3 - How can I conditionally validate (IValidatableObject) when calling UpdateModel or TryUpdateModel? 使用TryUpdateModel时的asp.net核心MVC控制器单元测试 - asp.net core mvc controller unit testing when using TryUpdateModel asp.net mvc 更新数据库中的项目时如何更新数据库(数据库未正确更新)? - asp.net mvc How do you update a database when you update an item in it (database not updating correctly)? 使用TryUpdateModel方法在ASP.NET MVC 3中使用EntityFramework更新多个对象 - Update multiple objects using EntityFramework in ASP.NET MVC 3 with TryUpdateModel method 为什么需要在ASP.NET MVC中的RoutesTable的默认路由中指定控制器和动作? - Why do you need to specify the controller and action in the default route for the RoutesTable in ASP.NET MVC? 在ASP.NET MVC(3.0 / Razor)中,您更喜欢视图中的多个视图或条件吗? 为什么? - In ASP.NET MVC (3.0/Razor), do you prefer multiple views, or conditionals within views? Why? 当我们在ASP.NET MVC中播种数据库时,为什么我们使用lamba表达式返回元素的id? - When we Seed a database in ASP.NET MVC, why do we use a lamba expression for returning the id of elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM