开发者

Modelbinding and generalization

I have a model where ClassC is inherited from classB.

ClassB

int b1

string b2

ClassC : ClassB

bool c1

int c2

string c3

My view is bound to ClassB. When I populate the model data for first time, I assign an instance of ClassC to variable of ClassB due to business need and then send it to view. Because ClassC is ClassB afterall.

In my view, I need to check the value of property c1 and make a div visible / invisible accordingly. So I access this property by following code

(Model as ClassC).c1

This works fine but only for first time. When I submit my page, the parameter of the controller accepts the model as of type ClassB.

public virtual ActionResult Save(ClassB classb)

But when I try to access the same property here, then the same code gives error of type casting. Ideally, shouldn't the parameter of ClassB contain the instance of ClassC which was assigned to it while populating view? It doesn't give any error in view! Is the modelbinder internally doing anything wrong here? How can I get this property in my controller in this 开发者_StackOverflow社区case? Any suggessions please? thanks..


Is the modelbinder internally doing anything wrong here?

No ModelBinding is doing exactly what it is trained to do. The job of modelbinder roughly is to get your action parameters and populate them from different sources (Fomr post, json, routevalue dictionary etc.). Since parameter of your action method is ClassB which does not contain properties (methods and fields) of ClassC so it will not populate those properties. Moreover, if you want to access ClassC in your action method you have to change it like

public virtual ActionResult Save(ClassC classc)
{
}

and as you said that you are using property of ClassC (c1) just to show/hide a div on the page. but if you want properties of Classc to be bound to model you have to put them in form fields (input, select, checkbox etc.) so they travel with request when the form is submitted.

Ideally, shouldn't the parameter of ClassB contain the instance of ClassC which was assigned to it while populating view?

No it should not because when the view is rendered and html is delivered to the user everything (Model, RequestContext etc.) is gone and when you submit the form, its totally a new request and is not supposed to contain model values from previous requests. The values of ClassB as you see in you action method do not come from previous request. its rather bound to your action parameters by the modelbinder.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜