代码之家  ›  专栏  ›  技术社区  ›  Pure.Krome

你能创建一个强类型的ASP吗。NET MVC ViewUserControl是int类型还是enum类型?

  •  4
  • Pure.Krome  · 技术社区  · 16 年前

    如。

    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 Type只能是类类型),然后执行以下操作。。

    <% Html.RenderPartial("AnimalFileImageControl", animalType); %>
    

    AnimalType animalType = (AnimalType) ViewData.Model;
        switch (animalType)
        { ... etc ... }
    

    1 回复  |  直到 16 年前
        1
  •  1
  •   Marc Gravell    16 年前

    好吧,你可以:

    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> 等等,但就我个人而言,我认为使用非类型化视图并简单地进行强制转换会更容易。

    推荐文章