何时以及为什么你在asp.net MVC 2使用TryUpdateModel? [英] When and why do you use TryUpdateModel in asp.net mvc 2?

查看:88
本文介绍了何时以及为什么你在asp.net MVC 2使用TryUpdateModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法找到只是一个基本的code样品,看看TryUpdateModel是如何工作的?当你使用它,为什么?

I can't seem to find just a basic code sample to see how TryUpdateModel works? When do you use it and why?

推荐答案

您可以使用此方法来更新备份通过给定控制器的特定视图模型。举例来说,如果我有显示通过一个文本框填充属性栏Foo对象的视图,我可以调用控制器上的方法保存(),并调用TryUpdateModel试图更新美孚

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.

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

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

这将尝试更新与酒吧的给定值模型。如果更新验证失败(比如,例如,酒吧是一个整数,文本框中有文字为你好),那么TryUpdateModel将通过验证错误更新的ViewData ModelState中,你的观点将显示验证错误。

This will try to update the model with the given value for 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.

请确保您密切关注MSDN文档中的安全警告用于.NET Framework 4:

Make sure you pay close attention to the security warning for .NET Framework 4 in the MSDN documentation:

安全注意使用之一
  [过载:System.Web.Mvc.Controller.TryUpdateModel``1]
  即它可以是一个列表方法
  属性包括:(白名单)或
  属性的列表中排除(一
  黑名单)。如果没有明确的白名单
  或黑名单通过,
  [过载:System.Web.Mvc.Controller.TryUpdateModel`1]
  方法尝试更新每个公共
  模型中的属性有哪些
  是在一个相应的值
  请求。恶意用户可能
  为了更新利用此
  你不打算性质
  提供访问。

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.

<一个href=\"https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.100).aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.100).aspx

这篇关于何时以及为什么你在asp.net MVC 2使用TryUpdateModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆