Get model type in MVC view

I use MVC4 and Razor and want to determine the type of model from the view. This should be easy, but I did not understand the syntax correctly.

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

It should be (I think) something like:

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

Any suggestions that were highly appreciated!

+6
source share
2 answers

You can use the is keyword:

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

as well (ugly):

 @if (Model.GetType() == typeof(Web.Models.AccommodationModel)) { <h1>Accomodation markup here</h1> } 
+12
source

Although you already have an answer, I would suggest that you rethink the whole concept.

What you are doing here is a combination of a common layout with certain views. These views may change in the future, requiring you to change the layout, there may be more and more, or some of them will be deleted. Thus, your approach violates the principle of shared responsibility: most have several reasons for changing _layout.cshtml.

How about pasting @section SomeSection { <h1>markup</h1> } in views that require such extra code, and rendering it in the layout using @RenderSection("SomeSection") , possibly also with @if(IsSectionDefined("SomeSection")) in the place where you want?

+4
source

Source: https://habr.com/ru/post/946759/


All Articles