Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Model type in MVC View

I'm using MVC4 and Razor and wish to determine the Model type from within a view. This should be easy but I'm not quite able to get the syntax correct.

I want to do this so I can conditionally display different markup in the _Layout.cshtml page depending on the current view and model that it's being used in.

It must be (I think) something along the lines of:

 @if (Model.GetType() == Web.Models.AccommodationModel) { // Obviously not correct
      <h1>Accomodation markup here</h1>
 }

Any suggestions much appreciated!

like image 452
WheretheresaWill Avatar asked Jun 07 '13 09:06

WheretheresaWill


People also ask

How do you get a ViewModel?

Go to solution explorer => Views Folder => Right-click on “Model” Folder >> go to “Add” >> Click on [Class] as follow. Provide the required name like “Product. cs” then click on “Add” button as follow.

How can we call model class in view in MVC?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.

How do you use a model in razor view?

Right-click in the Store Index action method and select Add View as before, select Genre as the Model class, and press the Add button. This tells the Razor view engine that it will be working with a model object that can hold several Genre objects.


3 Answers

You can use an extension method like this:

public static Type GetModelType<T>(this IHtmlHelper<T> html) => typeof(T);

This code returns the type even if the Model is null. Usage in razor:

@{ var type = Html.GetModelType(); }
like image 139
Alifvar Avatar answered Oct 18 '22 22:10

Alifvar


You could use the is keyword:

@if (Model is Web.Models.AccommodationModel) {
    <h1>Accomodation markup here</h1>
}

or also (uglier):

@if (Model.GetType() == typeof(Web.Models.AccommodationModel)) {
    <h1>Accomodation markup here</h1>
}
like image 23
Darin Dimitrov Avatar answered Oct 18 '22 21:10

Darin Dimitrov


Although you've already got an answer I would suggest you to rethink the entire concept.

What you're doing here is coupling the generic layout with some particular views. Those views can change in the future requiring you to change the layout, there can be more and more of them or some would be deleted. So your approach breaks Single Responsibility Principle: threre are obviously more than one reasons to change _layout.cshtml.

What about inserting a @section SomeSection { <h1>markup</h1> } in views requiring such additional code and rendering it in the layout using @RenderSection("SomeSection"), maybe also with checking @if(IsSectionDefined("SomeSection")) in the place you want?

like image 23
Bartłomiej Szypelow Avatar answered Oct 18 '22 21:10

Bartłomiej Szypelow