Pages

Monday, January 24, 2011

Display Image from a DB using MVC 2 & HtmlHelper

On a recent project, I wanted to extend the HtmlHelper to read in an image from a database and render it to my View using MVC 2. After various failed attempts and research, I put together a pretty simple way to accomplish my task.

The model

First we build out the model, which is pretty straight forward.

Model

the service

Next, we build the service call to get the image from the database by ID and return to us a populated model.

Service-GetContactPhoto

Now that we have the service and model setup and ready to go, we need to add a method to the controller that returns a FileContentResult. All the FileContentResult does is simply send the contents of a binary file to the response, which I will be using inside of the HtmlHelper.

the controller

Controller-GetPhoto

Again, pretty straight-forward as to how this works. I get the model from the service (in this case my service is contactService) and then return a File passing in the content byte[] and content type string.

Now to the HtmlHelper and actually rendering the image to the View.

the htmlhelper

HtmlHelper-ContactImage

First, we set the urlHelper to the requesting controllers Url. Then we call the urlHelper.Action which calls our controller method that we created earlier and passes in the pictureId. Finally, we use the TagBuilder to build an img tag, merge the src with the content from the controller, and return the tag to be rendered onto the View. You could extend this example and add in properties for the image ID, alt attribute, etc. if you wanted to.

Now, anytime you need to render an image from the database, you simply use the HtmlHelper, pass in the ID and that’s it!

View-CallHelper

As always, I want to hear your questions, comments, and feedback as to what I can do to make this better.

2 comments:

Robin Clowers said...

Isn't MergeAttribute for combining an existing value with an additional value (like adding a css style)? In this case you are just setting the src to a brand new value right?

Steve Hayes said...

@Robin -
You can use the MergeAttribute to replace an existing value, yes, however it uses a different method call: MergeAttribute(string, string, boolean)