marcus
marcus

Reputation: 10086

Default model binder always creates an instance?

I have an action that looks like this:

    public ActionResult Index(Home document) {

        return View(new BaseViewModel<Home>(document, _repository));
    }

but even though RouteData.Values["document"] does not exist the model binder creates an instance of Home. Is it possible to tell the model binder to give me null if the document is null?

Upvotes: 1

Views: 395

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You might need a custom model binder if you want to change this default behavior:

public class MyModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        // TODO: decide if you need to instantiate or not the model
        // based on the context
        if (!ShouldInstantiateModel)
        {
            return null;
        }
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

and then:

public ActionResult Index([ModelBinder(typeof(MyModelBinder))] Home document) 
{
    return View(new BaseViewModel<Home>(document, _repository));
}

or register it globally in Application_Start:

ModelBinders.Binders.Add(typeof(Home), new MyModelBinder());

Upvotes: 2

Related Questions