2014-10-30 2 views
1

나는 asp.net mvc 신청이있다. 다음과 같은 두 모델 클래스가 있습니다.MVC 모형 종류 주물

public class BaseViewModel 
{ 
    ... 
} 

public class DerivedViewModel : BaseViewModel 
{ 
    ... 
} 

나는이 모델을 모두 사용하고자합니다.

@model BaseViewModel 
... 

내부보기, I는 다음과 같이 사용할 수 있어요 :

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

이 같은이보기 내부의 양식을 사용하고 있습니다 :

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

을하지만 양식을 게시 할 때 컨트롤러 메서드를 사용하여 기본 클래스를 파생 클래스로 캐스팅 할 수 없습니다. 컨트롤러 메소드에서 파생 클래스와 기본 클래스를 분리하려면 어떻게해야합니까? 어떻게 올바르게 게시 할 수 있습니까?

+0

당신의 컨트롤러 동작을 표시합니다. – haim770

+1

모델 유형을 다음과 같이 확인하는 것이 좋습니다.'@if (Model is DerivedViewModel)' – haim770

+0

http://stackoverflow.com/questions/1524197/downcast-and-upcast –

답변

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