0

How do I find out the type of a View's Model within the View itself?

I tried doing calling GetType:

@model MyModel

<div>@Model.GetType()</div>

which works unless the Model is null, in which case I get a NullReferenceException.

Unfortunately it's also not possible to do

@model MyModel

<div>@typeof(TModel)</div>

as TModel is not available in the context of the Razor view.

dav_i
  • 27,509
  • 17
  • 104
  • 136

3 Answers3

6

Try:

@ViewData.ModelMetadata.ModelType

Works whether the model's value is null or not and it's built right in. No need for creating a helper.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
1

One way of doing this is by creating a helper extension on HtmlHelper<TModel>

public static class HtmlHelperExtensions
{
    public static Type GetModelType<TModel>(this HtmlHelper<TModel> helper)
    {
        return typeof(TModel);
    }
}

Which you can then use like so

@using HtmlHelperExtensions
@model MyModel

<div>@Html.GetModelType()</div>
dav_i
  • 27,509
  • 17
  • 104
  • 136
0

You could check to see if it's null first, then get the type, ie:

@if(Model != null) {
<div>@Model.GetType()</div>
}
dav_i
  • 27,509
  • 17
  • 104
  • 136
Andy Jones
  • 829
  • 11
  • 14
  • Thanks for your answer. Although this would solve the exception, it means that the type wouldn't be displayed if it is `null`. – dav_i Oct 13 '14 at 13:29
  • So you want the type, whether it is null or not? If that is the case, I believe you can not get the type of a null object. - You can see here for more information - http://stackoverflow.com/questions/930147/c-sharp-get-type-of-null-object. I think my solution is as close as you can get, if you add an "else" with "unknown type". – Andy Jones Oct 13 '14 at 13:46