Given a strongly typed view in ASP.Net MVC, is it possible to refer to the type parameter used to declare the view?
For example, if a page is declared as
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyProject.MyViewModel>" %>
is it possible to reference the type-parameter in ViewPage<TModel>?
I know I can do Model.GetType() but I have a situation where I have one view model derived from another, and both using the same view. I currently have a line like
<% if (Model.GetType().IsSubclassOf(typeof(MyViewModel)))
{ %>
to detect if the view is being used to display the derived model, but I’d like to be able to do it without hard-coding the typeof(...) call.
I want to do something like Model.GetType().IsSubclassOf(typeof(TModel))
If you create your own base class you can expose the model type via a property:
Change
to
The model type is exposed via this.ModelType