dav_i
dav_i

Reputation: 28137

How to get the Model type in a view

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.

Upvotes: 0

Views: 2131

Answers (3)

Chris Pratt
Chris Pratt

Reputation: 239430

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.

Upvotes: 7

Andy Jones
Andy Jones

Reputation: 869

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

@if(Model != null) {
<div>@Model.GetType()</div>
}

Upvotes: 0

dav_i
dav_i

Reputation: 28137

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>

Upvotes: 1

Related Questions