4

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 :)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

re: untyped view - same. That's what i'll go with to. Forgot about making a struct :P Nice idea, if i wanted to keep it strongly typed. Thanks again Marc :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.