Can you create a strongly typed ASP.NET MVC ViewUserControl of type int or enum?

I want to create a reusable ASP.NET MVC ViewUserControl that is strongly typed for enumeration.

Can this be done? When I try, it says that the strong type that ViewUserControl can accept can only be a reference type :(

It also means that I cannot pass int as a TModel.

Why do I want to do this? I’m in different places of my site, I show a simple image, which depends on the listing. Therefore, instead of copying this logic in several places, I want to have this resuable ViewUserControl and pass to the enumeration.

eg.

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%>" /> 

I assume that the solution would NOT be to create a strongly typed ViewUserControl (because the TModel type can only be a class type), and then do the following.

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

and in ViewUserControl ...

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

cheers :)

+4
source share
1 answer

well, you could:

 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); } } 

and use Box<int> , Box<MyEnum> , etc. - but personally, I expect it will be easier to use an untyped representation and just do it.

+1
source

All Articles