Friday, January 17, 2014

Step By Step How to retrieve data from the request using Model Binders

         By Carmel Schvartzman

In this tutorial we'll learn how to retrieve data from the request using Model Binders in an Action method  in ASP.NET MVC 4An Action method receives values from the HTTP request data collection, which includes data from the query string, form data, and cookies.

Each Controller has a Request and a Response properties, and from them is possible to obtain the values from the request:


Also, the MVC framework can automatically map the argument values to the Action method's parameters: the Controller looks over the sent request's parameters keys, and compares them to the names of the Action method parameters. If there is a mach, the value is assigned. If the parsing of the value fails, an exception is thrown:


The MVC framework is smart enough to deserialize an entire Entity, as follows:


That is because it uses a Model Binder, which deserializes the data request into an object, mapping every entity's public property to an request parameter, based on its key name. Also, the DefaultModelBinder keeps track of the state of the model binding, specifically of its errors. The ModelState class has a property called IsValid, which is very useful while determining the legal user input, according to data annotations of the entity.  
Finally, we can use another parameter type called FormCollection, wich contains all request data. Then is possible to call the UpdateModel method of the Controller to automatically populate the properties of an Entity with the values in the FormCollection. In order to do that, go to some Action method which handles HTTP POST requests, and take a look at the parameters: we'll use the FormCollection to initialize an Entity:



Create an instance of the same Entity sent into the request:


Now call the UpdateModel method of the Controller, to populate the object's public properties:


Next, we can for the learning sake fetch the data set by the UpdateModel method:


In an actual MVC application, we use the Repository we created in a previous tutorial , to update the post:


Let's take a look at the functionality. Build the application and browse to the Blog web page:


Press the "Edit" link to open the Edit dialog. You'll be redirected to the URL   /Blog/Edit/X  (where X is the id of the selected post):







Change some data, the Title , for example, and press "Save":


The selected post entry has been updated, using the default Model Binder:





In this tutorial we've learned how to retrieve data from the request using Model Binders in an Action method  in ASP.NET MVC
That's all!! 
Happy programming.....


כתב: כרמל שוורצמן

No comments:

Post a Comment