Can abstract class be a parameter in a controller's action?

前端 未结 5 1719
既然无缘
既然无缘 2020-12-31 03:53

I have an Action function inside of a Controller, which is being called with AJAX. That Action is taking in 1 parameter. Client side, I construct a JSON object which shoul

5条回答
  •  一向
    一向 (楼主)
    2020-12-31 04:29

    Update: Example now uses a AJAX JSON POST

    If you must use an abstract type, you could provide a custom model binder to create the concrete instance. An example is shown below:

    Model / Model Binder

    public abstract class Student
    {
        public abstract int Age { get; set; }
        public abstract string Name { get; set; }
    }
    public class GoodStudent : Student
    {
        public override int Age { get; set; }
        public override string Name { get; set; }
    }
    public class BadStudent : Student
    {
        public override int Age { get; set; }
        public override string Name { get; set; }
    }
    public class StudentBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var values = (ValueProviderCollection) bindingContext.ValueProvider;
            var age = (int) values.GetValue("Age").ConvertTo(typeof (int));
            var name = (string) values.GetValue("Name").ConvertTo(typeof(string));
            return age > 10 ? (Student) new GoodStudent { Age = age, Name = name } : new BadStudent { Age = age, Name = name };
        }
    }
    

    Controller Actions

    public ActionResult Index()
    {
        return View(new GoodStudent { Age = 13, Name = "John Smith" });
    }
    [HttpPost]
    public ActionResult Index(Student student)
    {
        return View(student);
    }
    

    View

    @model AbstractTest.Models.Student
    
    @using (Html.BeginForm())
    {
        

    Age @Html.TextBoxFor(m => m.Age)

    Name @Html.TextBoxFor(m => m.Name)

    }

    Added to Global.asax.cs

    protected void Application_Start()
    {
        ...
        ModelBinders.Binders.Add(new KeyValuePair(typeof(Student), new StudentBinder()));
    }
    

提交回复
热议问题