Using ModelBinder to Get an Object by ID

I have multiple controller actions that take id

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

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

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

      

I think it is best to use ModelBinder (SomeObjectFromIDModelBinder) for each action, so getting the object is decoupled from the controller and minify the action methods.

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

I think this is an appropriate use of ModelBinders (naming convention), but it just needs clarification. Thoughts?

0


source to share


2 answers


I decided that it was acceptable to do what I asked and have several ModelBinders that will bind different data to the model.



0


source


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

Alternatively, you can have a text field with the id "id" and a submit button on the form that submits to "/ Home / Get".



ModelBinders are meant so that you can have action methods, which are classes, instantiating and populating properties from form data, query string, or route data.

0


source







All Articles