Wednesday, November 12, 2008

How to display an image retrieved from DB in Monorail

Assume that I am developing a Castle Monorail Web application.

If I want to display an image retrieved from the database on a web page I can use a view template which looks similar to this one

<div>
  <table class="form">
    <tbody>
      <tr>
        <td>Title:</td>
        <td>${Form.TextField("model.Photo.Title")}</td>
      </tr>
      <tr>
        <td>Comment:</td>
        <td>${Form.TextArea("model.Photo.Comment")}</td>
      </tr>
      <tr>
        <td><button id="selectImage">Select</button></td>
        <td><img src="${UrlHelper.For({@action:@getPhoto})}?photoId=${model.Photo.Id}"/></td>
      </tr>
    </tbody>
  </table>
</div>

Note that I am using Brail as my view engine. I have an <img> element in the template. The src attribute of the <img> element points to the getPhoto method of the controller. The code in the controller which provides the photo is

public void GetPhoto(Guid employeePhotoId)
{
    var model = service.GetEmployeePhoto(employeePhotoId);
    Response.ContentType = "image/gif";
    Response.BinaryWrite(model.Photo.Image);
    CancelView();
}

Here the call to the service returns a model having a public field Photo. The class representing the photo has (among others) properties Title and Image, where Image is an array of bytes containing the photo itself (e.g. the content of a gif or jpg image).

No comments: