Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c# - 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? When do you use it and why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...