i wish to create a reusable ASP.NET MVC ViewUserControl which is strongly typed to an enumeration.
Can this be done? When i try it, it says that the strong type the ViewUserControl can accept, can only be of a reference type :(
This also means i can't pass an int as TModel.
Why do i want to do this? I'n various places of my site, i'm displaying a simple image which is dependant upon an enumeration. So instead of copying that logic in multiple places, I wish to have this resuable ViewUserControl and pass in 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'm guessin the solution would be to NOT create a strongly typed ViewUserControl (because TModel Type can only be of type class) and then do the following..
<% Html.RenderPartial("AnimalFileImageControl", animalType); %>
and in the ViewUserControl ...
AnimalType animalType = (AnimalType) ViewData.Model;
switch (animalType)
{ ... etc ... }
cheers :)
well, you could have:
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 would be easier to use an untyped view and simply cast.