且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC 2 - 绑定到抽象模型

更新时间:2022-05-01 02:47:37

如何为这个抽象类编写自定义模型绑定器:

How about writing a custom model binder for this abstract class:

public class CustomBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        // TODO: based on some request parameter choose the proper child type
        // to instantiate here
        return new Child();
    }
}

只有当您有一个表单,其中输入元素根据某些用户操作动态插入时,这才有意义.在这种情况下,您需要传递一些附加参数来指示您需要哪个具体类.否则我会坚持使用具体的视图模型作为动作参数.

This make sense only if you have a form where input elements are inserted dynamically based on some user action. In this case you need to pass some additional parameter to indicate which concrete class you need. Otherwise I would stick to concrete view models as action parameters.