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.
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 > OKStep-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.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
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcImageHandler { public class MyImageHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "Image/png"; var param = context.Request.QueryString["id"]; int id = 0; if (param != null && int.TryParse(param, out id)) { byte[] image = null; using (MyDatabaseEntities dc = new MyDatabaseEntities()) { image = dc.MyImages.Where(a => a.Id.Equals(id)).FirstOrDefault().ImageData; } //Cache TimeSpan cacheTime = new TimeSpan(1, 0, 0); context.Response.Cache.VaryByParams["*"] = true; context.Response.Cache.SetExpires(DateTime.Now.Add(cacheTime)); context.Response.Cache.SetMaxAge(cacheTime); context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.BinaryWrite(image); } } public bool IsReusable { get { return false; } } } }
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 codepublic ActionResult List() { List<MyImage> all = new List<MyImage>(); //MyDatabaseEntities is our datacontext using (MyDatabaseEntities dc = new MyDatabaseEntities()) { all = dc.MyImages.ToList(); } return View(all); }
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
@model IEnumerable<MvcImageHandler.MyImage> @{ ViewBag.Title = "List"; } <h2>List</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table> <tr> <th> @Html.DisplayNameFor(model => model.FileName) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.FileName) </td> <td> <img src="~/MyGenericHandler.ashx?id=@item.Id" /> </td> </tr> } </table>
Step-9: Run Application.
- How to upload image to database and show in a Page without image handler in MVC4.
- How to insert image into database and display in Gidview without Image Handler.