views:

39

answers:

1

Hi there, I'm building an asp.net mvc app that uses the default url route «/{controller}/{action}/{id}»

My problem is with the last item in this route, the id. The mvc framework automatically casts whatever in put in the id to the type of the parameter declared in the action.

example:

url: /mycontroller/myaction/1

public class mycontroller: Controller {

    public ActionResult myaction(int id)
    {
      // it works id == 1
    }

}

But if I declare in the action a parameter of a custom type the mvc framework is unable to map the last part of the route to the parameter.

example:

url: /mycontroller/myaction/xpto

public class mycontroller: Controller {

    public ActionResult myaction(MyType id)
    {
      // it fails to cast "xpto" to my type
    }

}

Where should I tap in the framework to teach it how to do it?

+2  A: 

Binding of values from the route data to an action argument is handled by the model binder. The default model binder is, unsurprisingly, DefaultModelBinder. If this type will not bind the value in your route to your MyType type, then you have two choices:

  • Change the date a you are passing in the route so that DefaultModelBinder can convert it to an instance of MyType without modification, or
  • Write a custom model binder, and set it as the model binder for your MyType type. If you Google ASP.NET MVC and model binders you will find examples of this.
Craig Stuntz
Great! That's it!I thought that the Model Binder worked just for Forms.
Gnomo