views:

734

answers:

4

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?

A: 

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

Craig Stuntz
+1  A: 

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.

Martijn Laarman
+1  A: 

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

aleemb
A: 

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:

http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx">ASP.NET MVC Preview 5 and Form Posting Scenarios

How to use the ASP.NET MVC Modelbinder

jrista