我似乎无法找到一个基本的代码示例来了解 TryUpdateModel 的工作原理?你什么时候使用它,为什么?
最佳答案
您可以使用此方法通过给定 Controller 更新支持特定 View 的模型。例如,如果我有一个显示 Foo 对象的 View ,该对象的属性 Bar 由文本框填充,我可以调用 Controller 上的方法 Save() 并调用 TryUpdateModel 来尝试更新 Foo。
public class Foo {
public string Bar { get; set; }
}
// ... in the controller
public ActionResult Save() {
var myFoo = new Foo();
TryUpdateModel(myFoo);
}
这将尝试使用 Bar 的给定值更新模型。如果更新验证失败(例如,Bar 是一个整数并且文本框中有文本“hello”),那么 TryUpdateModel 将通过更新 ViewData ModelState 并显示验证错误,并且您的 View 将显示验证错误。
请务必密切注意 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). 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. 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
关于c# - 何时以及为何在 asp.net mvc 2 中使用 TryUpdateModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5268421/