tags:

views:

207

answers:

2

I have multiple controller actions that takes an id

public ActionResult Get(int? id) {
...
}

public ActionResult Delete(int id) {
...
}

public JsonResult GetJson(int? id) {
...
}

I'm thinking its best practice to use a ModelBinder (SomeObjectFromIDModelBinder) on each action, so the obtaining of the object is separated from the controller, and keeps the action methods smaller.

The reason I don't want it to be called SomeObjectModelBinder is because I also have a need to recreate Models from JSON, so have a SomeObjectFromJsonModelBinder which handles recreating the 'SomeObject' from a JSON string.

I'm thinking this is a suitable usage of ModelBinders (naming convention), but just wanted clarification. Thoughts?

A: 

You don't need to do anything to get the ID. THe MVC handler will look for simple values of the same name as the method parameters in the Form data, the Query String, and the Route. So you could have a route /{controller}/{action}/{id} with defaults of action="Get", id=1. then the id could be specified in the URL as either /Home/Get/3 or /Home/Delete?id=6.

Alternately, you could have a textbox with an id of "id" and a submit button in a form that posts to "/Home/Get".

ModelBinders are intended to allow you to have action methods that are classes by creating the instance and populating the properies from the Form data, Query string, or Route data.

Matthew
I'm aware of this.What I want is the action method to provide to me the SomeObject rather than the integer id, removing the duplicated code across multiple actions in the controller.I'm after if it is correct to have multiple modelbinders for a single object and the naming convention for the binders
Luke Smith
A: 

I've decided that it is acceptable to do what I was asking, and having multiple ModelBinders that will bind different data to a Model.

Luke Smith