Tutorial :ASP.NET MVC model binding and action parameters



Question:

Let's say I have a controller action defined as:

public ActionResult(MyModel model, string someParameter)   {      // do stuff  }  

I have a custom model binder for the MyModel type, and there is a form field called "SomeParameter" in the view that is not bound to the model. How does ASP.NET MVC know to pass the value of Request.Form["SomeParameter"] as the value for the "someParameter" argument to the action?


Solution:1

Because the default model binder will be used for someParameter unless you specify otherwise. And the default model binder does exactly what you describe.


Solution:2

ASP.NET uses reflection to determine the correct method to invoke and to built up the parameters to pass. It does so based on the FormCollection array. Basically it will see model.* Keysin there and a FormCollection["someParameter"] it will first try Action(model,someParameter) then Action(model) and then Action(). Since it finds an Action with a model and someParameter arguments it will then try to convert them into the arguments types.

However by default it does so blindly which introduces some security risks, this blog post goes into greater detail on this.

If anyone can post up a link which in greater detail describes how ModelBinding is done under the hood that would be great.


Solution:3

Phil Haack has a post on How a Method becomes an Action which explains just how this resolution happens.


Solution:4

Sounds like you need a model binder. These allow you to define how form data is bound to a model parameter. You can read more about them at the following:

ASP.NET MVC Preview 5 and Form Posting Scenarios

How to use the ASP.NET MVC Modelbinder


Solution:5

One of the easiest way is having Html items on the page with same name as the input parameters in the action method. EX) In the View we have:

    <input name="refNo" type="text">  

Then in the Action method:

    public ActionResult getOrders(string refNo)  

So, it simply bind the value of "refNo" to the input parameter of the "getOrders" action.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »