ambrose
ambrose

Reputation: 11

Display Image from Database Using View Models MVC 5

Am working with the built-in template of visual studio 2013 mvc 5. am trying to display images i saved in the database to the index view of the home page.

the yellow highlighted sections are where i want to display the images

this is my view model for the images i want to display from the database

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HaveYouSeenMeApp.Models.ViewModels
{
    public class ImageViewModel
    {               
        public string PetPhotoName { get; set; }

        public byte[] Content { get; set; }

    }
}

this is my code in the home controller index method

using HaveYouSeenMeApp.Models;
using HaveYouSeenMeApp.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HaveYouSeenMeApp.Controllers
{
    public class HomeController : Controller
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index()
        {
            ApplicationDbContext db = new ApplicationDbContext();
            List<ImageViewModel> ImageViews = new List<ImageViewModel>();
            var ImageList = (from cust in db.PetPhotoSS select new { cust.PetPhotoName, cust.Content }).ToList();

            foreach(var item in ImageList)
            {
                ImageViewModel objcvm = new ImageViewModel();
                objcvm.PetPhotoName = item.PetPhotoName;
                objcvm.Content = item.Content;
                ImageViews.Add(objcvm);
            }
            return View(ImageViews);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

this is my code in the home index.cshtml

@model IEnumerable<HaveYouSeenMeApp.Models.ViewModels.ImageViewModel>

@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-large">Learn more &raquo;</a></p>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            <table>
                <tr>
                   <th> @Html.DisplayNameFor(model => model.PetPhotoName)</th>
                    <th>
                    @Html.DisplayNameFor(model => model.Content)</th>
                </tr>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.PetPhotoName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Content)
                        </td>
                    </tr>
                }
            </table>
        </p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>

Upvotes: 1

Views: 7939

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239460

You can't directly output image data to a view. You need an action to get the image data from the database and return it as a response. Then, in your view, you can add an <img> tag that references the URL to this action.

public ActionResult GetImage(int id)
{
    // fetch image data from database

    return File(imageData, "image/jpg");
}

Then:

<img src="@Url.Action("GetImage", new { id = 1 })" />

Alternatively, you could use Data URIs, but you would need to convert the image to a byte array first (if it's not a byte array already) and then base64 encode it. Then you could load it on the page with an <img> tag like:

<img src="data:[mimetype];base64,[data]" />

Where [mimetype] is the image's mime type (image/jpeg, for example) and [data] is the base64 encoded byte array. However, bear in mind that Data URIs are not supported in all versions of IE and even then, a Data URI will be much larger than the image itself. For example, a test image that's 44 KB was 62 KB as a Data URI. The exact size difference will depend on the image, but it will always be larger than the image file itself due to the base64 encoding. Additionally, since a Data URI is included in the HTML document itself, that means your initial payload is much larger as well, adding to the response and rendering time. With a typical image reference, the browser can render the HTML document and then fill in the images once those have completed downloading, but as Data URIs, the HTML document cannot be rendered until all the image data within it has been downloaded.

Upvotes: 3

Related Questions