如何为新的非复杂类型添加模型绑定支持?

时间:2014-01-10 05:55:53

标签: .net asp.net-mvc model-binding

我有一个控制器操作,它采用自定义类型的参数:

public class SomeController : Controller
{
    public ActionResult Index(CustomType someValue)
    {
        throw new NotImplementedException();
    }
}

ASP.NET MVC不知道自定义类型,它不是“复杂”类型;它需要自定义创建逻辑:

public class CustomType
{
    public CustomType(string data){}
}

在这个例子中,我希望能够告诉ASP.NET MVC,无论何时需要绑定到CustomType,它都应该使用以下过程:

(string someRequestValue) => new CustomType(someRequestValue)

我在这里快速浏览了一下Google,但我没有发现任何涉及这个简单场景的内容。

3 个答案:

答案 0 :(得分:1)

巴特的答案非常有效,我认为这适合你的情况。但是,如果您需要更改默认的模型绑定行为,最好通过实现公开单个方法IModelBinder

BindModel接口来实现您自己的模型绑定器对象。
public class CustomTypeModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueReceived = bindingContext.ValueProvider.GetValue("actionParam").AttemptedValue;
        return new CustomType(valueReceived);
    }
}

然后,只需在应用程序启动时注册模型绑定器......

protected void Application_Start()
{
       ModelBinders.Binders.Add(typeof(CustomType), new CustomTypeModelBinder());
}

但是,如上所述,你真的不需要走这条道路......我想

答案 1 :(得分:0)

根据Leo's answer的建议,可以通过实施IModelBinder并注册CustomType的实施来实现。通过支持任何操作参数而不仅仅是具有特定名称的参数,可以改进该实现。我还添加了空值检查,以便行为与内置模型绑定一致。

Model Binder

public class CustomTypeModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        var valueName = bindingContext.ModelName;
        var value = bindingContext.ValueProvider.GetValue(valueName);
        if (value == null)
            return null;

        var textValue = value.AttemptedValue;
        return new CustomType(textValue);
    }
}

注册

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(CustomType), new CustomTypeModelBinder());
}

答案 2 :(得分:-1)

为什么不:

public class SomeController : Controller
{
    public ActionResult Index(string someValue)
    {
        var obj = new CustomType(someValue);
    }
}