ASP.NET MVC 3通用DisplayTemplates [英] ASP.NET MVC 3 Generic DisplayTemplates

查看:189
本文介绍了ASP.NET MVC 3通用DisplayTemplates的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC 3,我建立在现有的对象系统之上,所以的第一件事情我要做的就是定义不同类型的显示和编辑模板中的一个刚开始的一个项目,存在的。

I've just started a project using ASP.NET MVC 3. I'm building on top of an existing object system, so one of the first things I have to do is define display and editor templates for the various types that exist.

是否有可能在MVC定义与通用参数的DisplayTemplate?例如,我们有一个 BITSTRING< T> 类,它需要一个枚举作为一般的参数,并重新presents选项包装附带的枚举列表。我希望我可以定义处理所有BITSTRING实例单显示/编辑模板。

Is it possible in MVC to define a DisplayTemplate with a generic argument? For example, we have a BitString<T> class which takes an enumeration as the generic argument and represents a list of options wrapping the supplied enumeration. I'm hoping I can define a single Display/Editor template that handles all BitString instances.

我目前使用的剃刀我的看法,但我不介意混合和匹配ASCX(或直C#是否有办法做到这一点),以实现这一目标。

I'm currently using Razor for my views, but I don't mind mixing and matching with ascx (or straight C# if there is a way to do it) to achieve this

感谢

编辑:
我觉得这可能是这个问题的DUP ......但这是一个一年半的历史,所以也许有人在这一点上一个更好的答案?
<一href=\"http://stackoverflow.com/questions/875085/generic-partial-view-how-to-set-a-generic-class-as-model\">Generic局部视图:?如何设置一个泛型类为模型

推荐答案

你所描述的问题是仿制药的基本原则。

The problem you're describing is a fundamental principal of generics.

的ICollection&LT;对象&gt; 不是基类的的ICollection&LT;弦乐&GT; 即使字符串是子类对象的。这是在编译时完成的,所以你基本上得到两个不同的ICollection的类定义。因此它们不能被铸造。 (这么聪明的人,请随时纠正我的任何错误)

ICollection<Object> is not the base class of ICollection<String> even if String is a child class of Object. This is done at compile time, so you basically get two different ICollection class definitions. Therefore they cannot be casted. (Smart people of SO please feel free to correct me on any inaccuracies)

在MVC3我已经解决这个通过执行以下工作:

In MVC3 I have worked around this by doing the following:

class Container{
  /* Stuff here */
}

class Container<T> : Container{
 T Data {get;set;}
}

然后在您的视图

@model Container 

当你只需要普通的东西不知道泛型类型。

When you need just the common stuff without knowing the generic type.

@model Container<SomeDataType>

在您需要的泛型类型的数据。

When you need the generic type data.

使用案例:

我创建一个存储里面我的模型ModelContainer级,具有可在局部显示页面错误信息的数组在一起。由于部分可以在每一页上使用,它不知道泛型类型是什么,因此需要此解决方法。

I create a "ModelContainer" class that stores my Model inside, together with an array of Error Messages that can be displayed the page in a partial. Since the partial can be used on every page, it does not know what the Generic type will be, so this workaround is needed.

如果您试图访问通用数据不知道它这类型不能使用。希望这能解决你的问题。

This cannot be used if you are trying to access the generic data without knowing its type. Hopefully this solves your problem.

这篇关于ASP.NET MVC 3通用DisplayTemplates的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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