我希望创建一个可重用的 ASP.NET MVC ViewUserControl,它被强类型化为枚举。
这能做到吗?当我尝试时,它说 ViewUserControl 可以接受的强类型只能是引用类型:(
这也意味着我不能将 int 作为 TModel 传递。
我为什么要这样做?我在我网站的各个地方,我正在显示一个依赖于枚举的简单图像。因此,与其在多个地方复制该逻辑,我希望拥有这个可重用的 ViewUserControl 并传入枚举。
例如。
public enum AnimalType
{
Cat,
Dog
}
// .. now code inside the view user control ...
switch (animalType)
{
case AnimalType.Cat: source = "cat.png"; text="cute pussy"; break;
... etc ...
}
<img src="<%=Url.Content("~/Images/" + source)%>" alt="<%=text%>" />
我猜解决方案是不创建强类型的 ViewUserControl(因为 TModel 类型只能是类类型),然后执行以下操作..
<% Html.RenderPartial("AnimalFileImageControl", animalType); %>
并在 ViewUserControl ...
AnimalType animalType = (AnimalType) ViewData.Model;
switch (animalType)
{ ... etc ... }
欢呼:)
最佳答案
好吧,你可以有:
public sealed class Box<T> where T : struct {
public Box(T value) { Value = value; }
public T Value { get; private set; }
public static explicit operator T(Box<T> item) {
return item.Value; } // also check for null and throw an error...
public static implicit operator Box<T>(T value) {
return new Box<T>(value); }
}
并使用
Box<int>
, Box<MyEnum>
等 - 但就我个人而言,我希望使用无类型 View 并简单地强制转换会更容易。
关于asp.net-mvc - 你能创建一个 int 或 enum 类型的强类型 ASP.NET MVC ViewUserControl 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/670317/