开发者

ASP.NET MVC View for data classes that have the same base class

开发者 https://www.devze.com 2022-12-21 23:31 出处:网络
I have an Edit page that has the base class as the data class, and it would show different editor form depending on which derived class the model is. However, after posting

I have an Edit page that has the base class as the data class, and it would show different editor form depending on which derived class the model is. However, after posting

[HttpPost]
public ActionResult Edit(BaseClassModel model)

the model here only holds values for the base class and cannot be cast back to the derived class.

H开发者_JAVA百科ow can this be solved?

thank you


Depending on the rest of your implementation, you can either

  • Prefer Encapsulation over Inheritance, having each of your current subclasses contain a complex property with all the common fields
  • Write your own ModelBinder (take a look at the DefaultModelBinder source for an example) and create it in Global.asax, eg: ModelBinders.DefaultBinder = new ComplexModelBinder();
  • Create a BaseClassModelBinderAttribute and mark each of your arguments with that, eg: public ActionResult Edit([BaseClassModelBinder] BaseClassModel model)
  • A combination of the above
0

精彩评论

暂无评论...
验证码 换一张
取 消