Model-binding an object from the repository by several keys

Posted by Anton on Stack Overflow See other posts from Stack Overflow or by Anton
Published on 2010-02-04T13:30:13Z Indexed on 2010/04/02 8:43 UTC
Read the original article Hit count: 285

Suppose the following route:

{region}/{storehouse}/{controller}/{action}

These two parameters region and storehouse altogether identify a single entity - a Storehouse. Thus, a bunch of controllers are being called in the context of some storehouse. And I'd like to write actions like this:

public ActionResult SomeAction(Storehouse storehouse, ...)

Here I can read your thoughts: "Write custom model binder, man". I do. However, the question is

How to avoid magic strings within custom model binder?
Here is my current code:

public class StorehouseModelBinder : IModelBinder
{
    readonly IStorehouseRepository repository;
    public StorehouseModelBinder(IStorehouseRepository repository)
    {
        this.repository = repository;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var region = bindingContext.ValueProvider.GetValue("region").AttemptedValue;
        var storehouse = bindingContext.ValueProvider.GetValue("storehouse").AttemptedValue;
        return repository.GetByKey(region, storehouse);
    }
}

If there was a single key, bindingContext.ModelName could be used...
Probably, there is another way to supply all the actions with a Storehouse object, i.e. declaring it as a property of the controller and populating it in the Controller.Initialize.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about model-binding