The model
First we build out the model, which is pretty straight forward.
the service
Next, we build the service call to get the image from the database by ID and return to us a populated model.
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
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
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!
As always, I want to hear your questions, comments, and feedback as to what I can do to make this better.
2 comments:
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?
@Robin -
You can use the MergeAttribute to replace an existing value, yes, however it uses a different method call: MergeAttribute(string, string, boolean)
Post a Comment