ASP.NET MVC 3: Output of a Specific View for a Specific Implementation

I have an IEnumerable base type as my model.

I need to display a different bit of HTML in the list depending on the specific type.

Thus, the resulting list may look something like this in HTML:

<ul> <li class="points">Points - Item 1 - 10 points <a href="#">Remove</a></li> <li class="media">Media - Item 2 - your_uploaded_image.jpg <a href="#">Remove</a></li> <li class="content">Content - Item 3 <a href="#">Remove</a></li> </ul> 

Most likely, I will add another type to this later, so solutions like the following are not really what I need.

 @foreach(var item in Model) { if(item is PointImpl) { var pointItem = item as PointImpl; <li class="points">Points - @pointItem.Name - @pointItem.Points points <a href="#">Remove</a></li> } else if(item is MediaImpl) { var mediaItem = item as MediaImpl; <li class="media">Media - @mediaItem.Name - @mediaItem.FileName <a href="#">Remove</a></li> } /* More implementations */ } 

I looked at the model metadata template tooltip, but that really doesn't help, because my model is IEnumerable ..

I was thinking of a custom Html Helper that looked at an attribute of a particular type, but thought there might be a built-in way to do this?

+2
source share
1 answer

Instead of the ugly foreach just use display templates:

 @model IEnumerable<SomeBaseViewModel> <ul> @Html.DisplayForModel() </ul> 

and then define display patterns for all child types. For instance:

~/Views/Shared/DisplayTemplates/PointImpl.cshtml :

 @model PointImpl <li class="points"> Points - @Model.Name - @Model.Points points <a href="#">Remove</a> </li> 

and: ~/Views/Shared/DisplayTemplates/MediaImpl.cshtml :

 @model MediaImpl <li class="media"> Media - @Model.Name - @Model.FileName <a href="#">Remove</a> </li> 

You see, no more, no more cycles, no more vars. Everything works by convention (templates should be located in the ~/Views/Shared/DisplayTemplates or ~/Views/SomeController/DisplayTemplates and should be named with a specific type - PointImpl.cshtml , MediaImpl.cshtml , ...). Based on the specific type, the corresponding display template will be displayed, and this is automatic for each element of the main model collection.

+6
source

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


All Articles