ASP.NET MVC 2 - Binding To Abstract Model

前端 未结 3 760
独厮守ぢ
独厮守ぢ 2020-12-09 05:36

If i have the following strongly-typed view:

<%@ Page Title=\"\" Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" Inherits=\"System.Web.Mvc.V         


        
3条回答
  •  死守一世寂寞
    2020-12-09 05:55

    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.

提交回复
热议问题