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!
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.
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.
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.
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(); }
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>
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With