ASP.NET MVC 3:具体实现输出特定视图 [英] ASP.NET MVC 3: Output specific view for concrete implementation

查看:148
本文介绍了ASP.NET MVC 3:具体实现输出特定视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IEnumerable基本类型,因为我的模型。

I have an IEnumerable of a base type as my model.

我需要根据具体类型是什么在一个列表中显示的HTML不同的位

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

所以,最终名单可能类似于此HTML中:

So the resulting list might look similar to 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>

这是可能我会另一种类型添加到这个后来让解决方案,如下面的是不是真的我后。

It's likely I will add another type to this later so solutions like the following aren't really what I'm after.

@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
   */
}

我看了一下模型元数据模板提示但这并不能真正帮助,因为我的模型是一个IEnumerable ..

I've had a look at model metadata template hint but that doesn't really help because my model is an IEnumerable..

我在想一个自定义的HTML帮助寻找的具体类型的属性,但认为有可能是一个建在这样的方式?

I was thinking about a custom Html Helper looking at an attribute on the concrete type but think there might be a built in way of doing this?

推荐答案

而不是丑陋的的foreach 只需使用显示模板:

Instead of the ugly foreach simply use display templates:

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

,然后定义显示模板所有子类型。例如:

and then define display templates for all child types. For example:

〜/查看/共享/ DisplayTemplates / PointImpl.cshtml

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

〜/查看/共享/ DisplayTemplates / MediaImpl.cshtml

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

请参阅,没有更多的如果,没有更多的循环,没有更多的增值经销商。一切工作按照惯例(模板必须位于〜/查看/共享/ DisplayTemplates 〜/查看/ SomeController / DisplayTemplates 文件夹,并应命名为具体类型的名称 - PointImpl.cshtml MediaImpl.cshtml 。 ..)。根据具体类型相应显示模板将被渲染,这会自动为主要模型集合的每个元素

See, no more ifs, no more loops, no more vars. Everything works by convention (templates must be situated in the ~/Views/Shared/DisplayTemplates or ~/Views/SomeController/DisplayTemplates folder and should be named as the name of the concrete type - PointImpl.cshtml, MediaImpl.cshtml, ...). Based on the concrete type the corresponding display template will be rendered and this automatically for each element of the main model collection.

这篇关于ASP.NET MVC 3:具体实现输出特定视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆