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

标签 c# asp.net asp.net-mvc

我似乎无法找到一个基本的代码示例来了解 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/

相关文章:

asp.net - 如何传递日期时间参数?

c# - 在 C# 中获取服务器计算机文件夹中的临时文件名

asp.net-mvc - MVC DropDownListFor 获取 2 个名字

c# - 使用使用空格的字符串文字保持代码结构

c# - UWP 无法通过 FolderPicker 从硬盘访问文件夹

c# - 如何检索运行 Windows 服务的用户名?

c# - 合并与空字符串连接

c# - 从 jquery ajax 调用 webmethod 和静态对象的问题

asp.net-mvc - TypeScript 未使用 WE3 和 TS 0.9.1.1 进行编译

c# - KnockOut.js 与 Asp.net mvc