Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
user603007 Avatar asked Mar 11 '11 02:03

user603007


People also ask

What does TryUpdateModel do?

TryUpdateModel<TModel>(TModel)Updates the specified model instance using values from the controller's current value provider.

What is meaning of @: In .NET MVC?

Using @: to explicitly indicate the start of content We are using the @: character sequence to explicitly indicate that this line within our code block should be treated as content.

What is a view model in MVC?

In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

What is ASP NET MVC life cycle?

The life cycle is basically is set of certain stages which occur at a certain time. MVC actually defined in two life cycles, the application life cycle, and the request life cycle. The Starting point for every MVC application begins with routing.


1 Answers

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

like image 144
Martin Doms Avatar answered Oct 02 '22 18:10

Martin Doms