0

Well,

Let's suppose that I have two Model classes:

public class BaseClass{
    public Int32 variable {get;set;}
}

public class DerivatedClass : BaseClass{
    public Int32 otherVariable {get;set;}
} 

And a View with BaseClass type as Model.

If I pass a DerivatedClass to the View and retrieve information through a form, it wouldn't be "castable" to DerivatedClass again?

The problem is that if I retrieve the Model's type inside the view (Model.GetType().FullName), I get (without surprises) a DerivatedClass type.

But when I check the model posted, inside my controller, I get a BaseClass (and obviously, it can't be casted!)

Controller:

public ActionResult ViewPage(){
    return View(new DerivatedClass());
}

[HttpPost]
public ActionResult ViewPage(BaseClass b){
    b.GetType().FullName;                 //Gives me Project.packeges.BaseClass.
    DerivatedClass d = (DerivatedClass)b; //Ops, It can't be done. Exception.
}

View:

@model Project.packeges.BaseClass

<h3>@Model.GetType().FullName</h3>  
<!-- Gives me Project.packeges.DerivatedClass -->
...

Is my logic wrong? There's anyway to do this cast inside the controller after retrieve the POST information?

tereško
  • 58,060
  • 25
  • 98
  • 150
igor.araujo
  • 1,007
  • 1
  • 7
  • 15
  • What exactly are you trying to achieve? The whole point of having a model type is to be able to have a type for MVC to *model* your data after. Specifying a different type than you actually want to use in the view is self defeating. – M.Babcock Feb 24 '12 at 04:13
  • Maybe I'm wrong... But I think that I would be useful if we could reuse a view with a base class model to it's child classes... It's one of the pilars of the OOP isn't it? Code reuse? – igor.araujo Feb 24 '12 at 18:47

1 Answers1

1

Model binder will create an object of BaseClass and try to assign properties.

So when control come to your post action, it will have instance on BaseClass not the child class.

So, it is throwing exception while down casting.

Your requirement can be achieve through a CustomModelBinder and Create Instance on DerievedClass when BaseClass instance is asked for.

I have answered a similar post, with complete description.

Please have a look into "MyPost".This might be what you are looking for.

Community
  • 1
  • 1
Manas
  • 2,534
  • 20
  • 21
  • I think that the post you said can help me out. But... If I need to choose between two derivated classes inside the CreateModel? – igor.araujo Feb 24 '12 at 18:45
  • Nevermind... I was able resolve my problem. Thanks Manas. Now I better understand how do the ModelBinder pass the info to the controller after the POST. – igor.araujo Feb 24 '12 at 19:28