views:

59

answers:

3

I am playing around with an ASP.MVC site, I want one of three images to be displayed depending on the value of an enum in the strongly typed model I have.

I could use an IF/Case statement in the view but it should be the responsibility of the controller I feel, what's the best way to implement this?

+1  A: 

If you have an Enumerable<YourModel>, You may want to provide a Dictionary<YourEnum, Uri> from the controller to the view.

That way, the controller can decide what valid images there are, and etc.

However, choosing an image seems like a fundamentally view-bound activity. As an exercise, imagine how you would handle this if the controller we actually driving a WinForms app rather than a web app.

If it were me, I would use a Dictionary<YourEnum, string>, where the values in the dictionary were the names of the images. I would then use URL routing to choose where the browser should pick up the images.

John Gietzen
+1 that's a good idea.
Tony Abrams
I like the part about using the image name a lot, but if the view is going use the name to decide what image to show on its own (via routing), why pass all the image names and the selector at the same time?
NickLarsen
+1  A: 

I would just have the controller pick an image and then pass the image to the view. On the view just use the passed value to render out the image.

Tony Abrams
+1, it's the controllers job.
NickLarsen
@NickLarsen: Well, it's the controller's job to decide which representation to use. It is already doing that by specifying the Enum. The controller should potentially be able to drive a WPF app or similar that may not have any understanding of "~/Images/blah.png", and may instead have embedded resources. So, I would say that it is the View's job to decide from where to pull the images.
John Gietzen
Thats a good point, but if you're going to modify the controller to populate a dictionary to pass along to the view as well, the view will still depend directly on the controller, not the view model. Unless you remove that coupling, it is the controller's job.
NickLarsen
A: 

view:

<img src='<% Html.RenderAction("ImageSrc","Home",new { EnumValue = x });%>' />

controller:

public ActionResult ImageSrc(int EnumValue)
{
   string image = .....(EnumValue);
   return Content(image);
}
Omu