-->

How to Display image from database using Generic Handler in ASP.Net MVC4 application



Introduction

In this post, I am explain How to Display image from database using Generic Handler in ASP.Net MVC4 application.
In my previous Article I have expainted How to upload image to database and show in a Page without image handler in MVC4. Here I would like to explain How to Display image from database using Generic Handler in ASP.Net MVC4 application.

The previous Article How to upload image to database and show in a Page without image handler in MVC4. , is good because it Removes separate HTTP Requests for loading image from database and is suitable when used for very few images. But there is some limitation as well
  • Its increase image size approximately 20-25%.
  • If you put the base64 image directly in a page, it won't be cached separately.
We will overcome those limitations in this article.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for Store Images.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Generic handler for Fetch Image from Database and return image content to the response stream.

Right Click on Solution Explorer > Add > New Item > Select Generic Handler under web > Enter name > Add.

Here We will pass the Id parameter as a querystring parameter to our handler and then we will fetch image data from database based on id value . After that, we will write the image content to the response stream using the BinaryWrite method. To display the image, we will use <img src="~/ourGenericHandler.ashx?id=1"/>
Write following code to the handler

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. namespace MvcImageHandler
  7. {
  8. public class MyImageHandler : IHttpHandler
  9. {
  10.  
  11. public void ProcessRequest(HttpContext context)
  12. {
  13. context.Response.ContentType = "Image/png";
  14. var param = context.Request.QueryString["id"];
  15. int id = 0;
  16. if (param != null && int.TryParse(param, out id))
  17. {
  18. byte[] image = null;
  19. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  20. {
  21. image = dc.MyImages.Where(a => a.Id.Equals(id)).FirstOrDefault().ImageData;
  22. }
  23.  
  24. //Cache
  25. TimeSpan cacheTime = new TimeSpan(1, 0, 0);
  26. context.Response.Cache.VaryByParams["*"] = true;
  27. context.Response.Cache.SetExpires(DateTime.Now.Add(cacheTime));
  28. context.Response.Cache.SetMaxAge(cacheTime);
  29. context.Response.Cache.SetCacheability(HttpCacheability.Public);
  30. context.Response.BinaryWrite(image);
  31. }
  32. }
  33.  
  34. public bool IsReusable
  35. {
  36. get
  37. {
  38. return false;
  39. }
  40. }
  41. }
  42. }

Step-6: Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-7: Add new action into your controller for show Image in view.

Here I have added "List" Action into our Controller. Please write this following code

  1. public ActionResult List()
  2. {
  3. List<MyImage> all = new List<MyImage>();
  4. //MyDatabaseEntities is our datacontext
  5. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  6. {
  7. all = dc.MyImages.ToList();
  8. }
  9.  
  10. return View(all);
  11. }

Step-8: Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.
[N:B:Please Rebuild solution before add view.]
Complete View
  1. @model IEnumerable<MvcImageHandler.MyImage>
  2. @{
  3. ViewBag.Title = "List";
  4. }
  5.  
  6. <h2>List</h2>
  7.  
  8. <p>
  9. @Html.ActionLink("Create New", "Create")
  10. </p>
  11. <table>
  12. <tr>
  13. <th>
  14. @Html.DisplayNameFor(model => model.FileName)
  15. </th>
  16. <th></th>
  17. </tr>
  18.  
  19. @foreach (var item in Model) {
  20. <tr>
  21. <td>
  22. @Html.DisplayFor(modelItem => item.FileName)
  23. </td>
  24. <td>
  25. <img src="~/MyGenericHandler.ashx?id=@item.Id" />
  26. </td>
  27. </tr>
  28. }
  29.  
  30. </table>
  31.  

Step-9: Run Application.

Download     Live Demo


Related Post : 

  1. How to upload image to database and show in a Page without image handler in MVC4.
  2. How to insert image into database and display in Gidview without Image Handler.


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

Related Posts: