2014-10-30 162 views
1

我有一个asp.net mvc应用程序。我有两个这样的模型类:MVC模型类铸造

public class BaseViewModel 
{ 
    ... 
} 

public class DerivedViewModel : BaseViewModel 
{ 
    ... 
} 

我有一个看法,我想使用这两种模型的视图。

@model BaseViewModel 
... 

内部视图,我可以用这样的:

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

我使用这个观点像这里面的一种形式:

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

但是当我发布形式控制器方法,我无法将基类投射到派生类。如何在控制器方法中分离派生类和基类?我如何正确发布?

+0

显示你的控制器动作。 – haim770 2014-10-30 15:06:24

+1

你最好检查这样的模型类型:'@if(模型是DerivedViewModel)' – haim770 2014-10-30 15:07:21

+0

回答了在http://stackoverflow.com/questions/1524197/downcast-and-upcast – 2014-10-30 15:23:46

回答

1

拍下这一刻:

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

像素类从点继承,所以像素对象将指向特性,而不是其他方式。看看:

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 :) 

现在,用这些对象,你可以执行铸造。但取决于每种方式,你将会做一个向下转换或向上转换。

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 

对于更深层次的信息,尝试本文来自菲尔·科诺: Polymorphism, Up-casting and Down-casting