Returning Byte Array Data in ASP.NET MVC

Assume you have the following ASP.NET MVC model which contains a byte array property which will be used to hold data for an image.

    public class CompanyModel
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public byte[] Logo { get; set; }
    }

On the controller side, you fetch the data from the database using code similar to the following

    public ActionResult Settings(string countyId)
    {
        var county = _session.Get <CompanyModel>(countyId);
        return View(model);
    }

On the view, we convert the byte array to base64 string and use data URI to set the image source. Data URLs take the following format:

    data:[<mediatype>][;base64],<data>;

This will display the image without making a round trip to the database to fetch the image.

To persist the byte array data on the view, we define a hidden input which will be assigned the base64 string string value. The name and id for the input has to match the name of the property of our model containing the byte array.

    @{
        byte[] logo = Model.Logo;
        string logoSrce = null;
        string imgBase64 = null;
        if (logo != null)
        {
        var ms = new MemoryStream();
        ms.Write(logo,0,logo.Length);
        imgBase64 = Convert.ToBase64String(logo.ToArray());
        logoSrce = string.Format("data:image/png;base64,{0}", imgBase64);
        }

        <input id="Logo" name="Logo" type="hidden" value="@imgBase64" />
        <img src="@logoSrce" style="width: 120px; height: 120px;" />
    }