默认模型绑定器总是创建一个实例?

时间:2011-02-05 16:40:50

标签: c# c#-4.0 asp.net-mvc-3

我有一个看起来像这样的动作:

    public ActionResult Index(Home document) {

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

但即使RouteData.Values [“document”]不存在,模型绑定器也会创建Home的实例。如果文档为空,是否可以告诉模型绑定器给我null?

1 个答案:

答案 0 :(得分:2)

如果要更改此默认行为,则可能需要自定义模型绑定器:

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);
    }
}

然后:

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

或在Application_Start中全局注册:

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