1

I have an asp.net mvc application. I have two model class like this:

public class BaseViewModel
{
    ...
}

public class DerivedViewModel : BaseViewModel
{
    ...
}

I have a view and I want to use this view both of these models.

@model BaseViewModel
...

Inside view, I am able to use like this:

@if (Model.GetType() == DerivedViewModel)){
@* Properties of Derived class *@
}

I am using a form inside this view like this:

@using (Html.BeginForm("Home", "Application", FormMethod.Post)) {
...
}

But when I post the form to controller method, I can't cast base class to derived class. How can I separate derived and base class in the controller method? How can I post correctly?

3

1 Answer 1

2

Picture this:

class Point
{
    int x { get; set; }
    int y { get; set; }
}
class Pixel : Point
{
    string RGB { get; set; }
}

The Pixel class inherits from Point, so a Pixel object will have Point features, but not the other way. Take a look:

var point = new Point { x = 1; y = 10; } // point object do not have RGB property;
var pixel = new Pixel { x = 1; y = 10; RGB = "#FFF" } // no comments needed :)

Now, with theses objects, you may perfom casting. But depending on each way, you will be doing a downcasting or an upcasting.

var pointOfPixel = (Point)pixel; // upcasting, but will "loose" the RGB property
var pixelFromPoint = (Pixel)point; // downcasting, a RGB property will be available with no value

For deeper information, try this article from Phil Curnow: Polymorphism, Up-casting and Down-casting

Not the answer you're looking for? Browse other questions tagged or ask your own question.