Display Binary Images In WebGrid From Database

WebGrid

For this demo, I am going to use Visual Studio 2012 and SQL Server.

Database Part

Let’s start with the database part first.

I already have a database with the name OrderDB1, and inside that I have a table with the name FileTB.

It has two columns; one is File Name, and another one is Filebytes. Filename will store the name of the file, and Filebytes will store bytes of images.

Below is a snapshot of the OrderDB1 database.

OrderDB1 database

Below is a snapshot of FileTB table.

FileTB table

After completing it by adding the table in the database, now let’s move forward and create a new project in MVC for inserting data and displaying inserted data WebGrid.

Creating an MVC application

From Visual studio IDE select File Menu right at the top;  inside that select New, then click on Project.

click on Project

After clicking on Project, a New Project Wizard will pop up.

Inside that select Templates, then Visual C#;  inside this select Web. After selecting you will see various Project Templates (Webforms , MVC , ASP.NET AJAX Server control) in this select “ ASP.NET MVC 4 Web Application,” after selecting,  just name your Project “WebGridwithImages” and finally click on the OK button to create the project.

Selecting Templates

After clicking on the Ok button to create a project a new dialog will pop up with the name “New ASP.NET MVC 4 Project”. In this project template just select Basic Template and then in View Engine select Razor and click the Ok button.

Basic Template

Wait for some tim -- it requires some seconds for configuringa solution for you.

After creating the project,  here is your project ready for you.

It containsa whole lot of MVC folder structure and other script and .css styles.

MVC folder structure

After successfully creating the application now let’s add ADO.NET Entity Data Model for inserting and retrieving data from the database.

Adding ADO.NET Entity Data Model

For adding ADO.NET Entity Data Model just right click on Models folder and from list select Add, then select ADO.NET Entity Data Model.

Model - Add, then ADO.NET Entity Data Model.

ADO.NET Entity Data Model

After selecting, a new dialog will pop up with the name “Specify Name for Item.” I have entered name MvcOrderDb. You can specify as per your requirement and then click on the Ok button.

After that a new Wizard will pop up.

Choosing Data Connection

From that select Generate from database and click the Next button.

After clicking the Next button a New Wizard will pop up for Choosing Data Connection.

Choosing Data Connection:

click on OK button

After clicking on New Connection a new dialog of Connection Properties will pop up.

Let’s configure it.

In Server Name you need to add your SQL Server Name.

Using SQL Server Authentication you need to enter User name and Password of Sql server.

Lastly I am going to select Database Name: OrderDB1.

Click on the OK button.

Entity Data Model Wizard

After adding, the Entity Data Model Wizard will look like the following screenshot:

Selecting database objects

Selecting database objects

Now click on Next button.

A new wizard will pop up for selecting database object and in this you will see the entire table which we have created in the database. But for this demo we are going to need only one table, FileTB.

table

At lastly click on the Finish button.

Here is the screenshot after adding ADO.NET Entity Data Model.

Model

After adding ADO.NET Model now let us add Controller and Action Method.

Adding Default1 Controller

For adding Default1Controller just right click on the Controllers folder, inside that,  select Add and then select Controller.

Add Default1 Controller

After clicking on Controller a new dialog will pop up withthe name Add Controller.

Add Controller

In this dialog, to add Controller we are not going to make any change, just click on the Add button to add a Controller with the default name “Default1Controller”.

Code snippet of Default1Controller when added for the first time

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace WebGridwithImages.Controllers  
  8. {  
  9.     public class Default1Controller : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Default1/  
  13.   
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.   
  19.     }  
  20. }  
Now after adding Controller,  let’s add two Actions: one for handling HttpGet Request, and another for handling HttpPost Request for Inserting Images in Database.

We are going to add two Action Methods with name UploadImages().

Adding 2 Action Method to Default1Controller

  1. [HttpGet]  
  2. public ActionResult UploadImages()  
  3. {  
  4.     return View();  
  5. }  
  6.   
  7. [HttpPost]  
  8. public ActionResult UploadImages(HttpPostedFileBase uploadFile)  
  9. {  
  10.   
  11.  return View();  
  12.   
  13. }  
Code Snippet of Default1Controller
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using WebGridwithImages.Models;  
  8.   
  9. namespace WebGridwithImages.Controllers  
  10. {  
  11.     public class Default1Controller : Controller  
  12.     {  
  13.          
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.   
  19.         [HttpGet]  
  20.         public ActionResult UploadImages()  
  21.         {  
  22.             return View();  
  23.         }  
  24.   
  25.         [HttpPost]  
  26.         public ActionResult UploadImages(HttpPostedFileBase uploadFile)  
  27.         {  
  28.             OrderDB1Entities ODB = new OrderDB1Entities(); // DbContext  
  29.   
  30.             FileTB objfiletb = new FileTB(); // object of table  
  31.   
  32.             HttpPostedFileBase httpobj = Request.Files["file"];  
  33.   
  34.             string[] Filename =httpobj.FileName.Split('.');  //Spliting Image Name to Get FileName  
  35.   
  36.             objfiletb.FileID = 0;  
  37.             objfiletb.FileName = Filename[0];   
  38.   
  39.             using (Stream inputStream = Request.Files[0].InputStream) //File Stream which is Uploaded  
  40.             {  
  41.                 MemoryStream memoryStream = inputStream as MemoryStream;  
  42.                 if (memoryStream == null)  
  43.                 {  
  44.                     memoryStream = new MemoryStream();  
  45.                     inputStream.CopyTo(memoryStream);  
  46.                 }  
  47.                 objfiletb.Filebytes = memoryStream.ToArray();  
  48.             }  
  49.   
  50.             ODB.FileTBs.Add(objfiletb);   
  51.             ODB.SaveChanges(); //Inserting Image and details in Database  
  52.             return View();  
  53.         }  
  54.   
  55.     }  
  56. }  
Explanation of Above Code Snippet

In UploadImages Post Request we are going to create an object of DBcontext class [OrderDB1Entities] which is required for Inserting data.

This DBcontext class is located in ADO.NET Entity Data Model files which we have added earlier [MvcOrderDb.edmx].

After that we are going to Create Object of [FileTB] Class; that is your Model.  We are going to Assign Values to this Model and then Pass it to FileTBs DbSet [ ODB.FileTBs.Add(objfiletb); ] after assigning value to the model, to save data finally  call ODB.SaveChanges(); //Inserting Image and details in Database.

Adding View [UploadImages]

After adding Controller and Action Method now let’s add View to this Action Method [UploadImages].

For adding View, from just right inside UploadImages Action Method  from List select Add View;  after selecting Add View a new dialog of Add View will pop up.

If view is the same name as that of Action Method we are not going to make a change to it. After that we are going select View engine --  that’s Razor. Then we are going to create a strongly typed View --  for that select Model FileTB, and in Scaffold template we are going to select Empty template. If you want layout then check the given option. Finally , click on the Add button. This view will get added in the View folder; inside that there will a folder with the name of controller Default1 and inside that, this view will be placed.

click on Add button

Locating View

Locating View

After adding view now let us begin with Add control for file upload and button to submit this file to the server.

Complete code snippet of UploadImages View.

In this view I have added a file upload control and a button control.
  1. @model WebGridwithImages.Models.FileTB  
  2.   
  3. @{  
  4.     ViewBag.Title = "UploadImages";  
  5. }  
  6.   
  7. <link href="~/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet" />  
  8. <script src="~/Scripts/jquery-1.9.1.js"></script>  
  9. <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>  
  10.   
  11. @using (Html.BeginForm("UploadImages""Default1", FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal", role = "form" }))  
  12. {  
  13.     <div class="container" >  
  14.         <h3>UploadImages</h3>  
  15.         <div class="form-group">  
  16.             <label for="file">Filename:</label>  
  17.             <input type="file" name="file" id="file" />  
  18.         </div>  
  19.         <div class="form-group">  
  20.              <button type="submit" class="btn btn-default">Submit</button>  
  21.         </div>  
  22.     </div>  
  23. }  
What does enctype='multipart/form-data' mean

The enctype='multipart/form-data is an encoding type that allows files to be sent through a POST.

Quite simply, without this encoding the files cannot be sent through POST.

If you want to allow a user to upload a file via a form, you must use this enctype.

Now just save and run your Application Add Images to database.

UploadImages View for Inserting Images.

UploadImages

After inserting few images in database.

FileTB snapshot after inserting Images

FileTB

Now we have come to final main topic where we want to display images in WebGrid,  which is stored in binary format in the database.

Adding New Action Method Show Images in Default1Controller

To display images in WebGrid we are going to add a new Action Method with the name ShowImages.

The ShowImages Action Method going to return a list of image names and binary data to display on View.
  1. [HttpGet]  
  2. public ActionResult ShowImages()  
  3. {  
  4.    OrderDB1Entities ODB = new OrderDB1Entities(); //DBcontext class   
  5.    var listofpic = ODB.FileTBs.ToList(); // Get List of images stored in FileTB table  
  6.    return View(listofpic);  
  7. }  
After adding Action Method let's add View to the Action Method ShowImages.

For adding View just right inside ShowImages Action Method and from list select Add View. After selecting Add View a new dialog of Add View will pop up.

If view is the same name as that of Action Method we are not going to make a change to it. After that we are going select View engine -- that’s Razor. Then we are going to create a strongly typed View --  for that we are going to select Model [FileTB] and in Scaffold template we are going to select Empty template.

If you want layout then check the given option. Finally, click on the Add button. This view will get added in View Folder, inside that, there will a folder with the name of controller Default1,  inside that this view will be placed.

Adding View [ShowImages]

Adding View

After adding View we are going to add some script of Bootstrap and WebGrid to display data.

Adding .css and Script Reference to [ShowImages] View

Let’s start with adding script and .css first.
  1. <div style="margin-left: 50px; margin-right: 50px; margin-top: 50px;">  
  2.     @{    
  3.         var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);  
  4.         grid.Pager(WebGridPagerModes.All);  
  5.     }  
  6.   
  7.      @grid.GetHtml(  
  8.            htmlAttributes: new { id = "gridMapping" },  
  9.            tableStyle: "table table-bordered",  
  10.            headerStyle: "info",  
  11.            footerStyle: "webgrid-footer",  
  12.            alternatingRowStyle: "webgrid-alternating-row",  
  13.            selectedRowStyle: "webgrid-selected-row",  
  14.            rowStyle: "gridrow",  
  15.            columns: grid.Columns  
  16.            (  
  17.            grid.Column("FileName""FileName"null, style: "name"),  
  18.            grid.Column(header: "Images", format:   
  19.            @<text>  
  20.              <img id="imagebtn"   
  21.                   onclick="ZoomImage('data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))')"   
  22.                   src="data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))"    
  23.                   width="70px"   
  24.                   height="70px"    
  25.                   alt="@item.FileName" />  
  26.            </text>, style: "Imagepix"))  
  27.      )  
  28. </div>  
After adding script and .css now we are going to add WebGrid and to this WebGrid we are going to pass a list of FileTB Model.

Code snippet of WebGrid which display Images on [ShowImages] View
  1. <div style="margin-left: 50px; margin-right: 50px; margin-top: 50px;">  
  2.     @{    
  3.         var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);  
  4.         grid.Pager(WebGridPagerModes.All);  
  5.     }  
  6.   
  7.      @grid.GetHtml(  
  8.            htmlAttributes: new { id = "gridMapping" },  
  9.            tableStyle: "table table-bordered",  
  10.            headerStyle: "info",  
  11.            footerStyle: "webgrid-footer",  
  12.            alternatingRowStyle: "webgrid-alternating-row",  
  13.            selectedRowStyle: "webgrid-selected-row",  
  14.            rowStyle: "gridrow",  
  15.            columns: grid.Columns  
  16.            (  
  17.            grid.Column("FileName""FileName"null, style: "name"),  
  18.            grid.Column(header: "Images", format:   
  19.            @<text>  
  20.              <img id="imagebtn"   
  21.                   onclick="ZoomImage('data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))')"   
  22.                   src="data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))"    
  23.                   width="70px"   
  24.                   height="70px"    
  25.                   alt="@item.FileName" />  
  26.            </text>, style: "Imagepix"))  
  27.      )  
  28. </div>  
In the above code I have used Image tag to display Image, but images stored in database are in binary [byte[]] format and we cannot directly display binary image on View.

For displaying those [byte[]] we have to convert it to base 64 string as in the following:
  1.   [@(Convert.ToBase64String(item.Filebytes))]   
  2.   
  3.   
  4.    @<text>  
  5.   <img id="imagebtn"   
  6.        onclick="ZoomImage('data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))')"   
  7.        src="data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))"    
  8.        width="70px"   
  9.        height="70px"    
  10.        alt="@item.FileName" />  
  11. </text>,  
After completing with Adding Style, Css and WebGrid now save your Application and Access Action Method [ShowImages].

ShowImages View for Displaying Images in WebGrid

Displaying Images in WebGrid


We have finally displayed images in WebGrid,  but the images are too small to view.

Let’s display large Images as we click on the Image displayed in WebGrid.

Adding code snippet of JavaScript function for displaying large images on click of image

For that, I am going add JavaScript code, which will take the image as input and display that Image in a Large Popup.

This function will get called when we are going to click on the image.
  1. <script type="text/javascript">  
  2.     function ZoomImage(image) {  
  3.           
  4.         document.getElementById("main").src = image;  
  5.         $("#popupdiv").dialog({  
  6.             width: 600,  
  7.             height: 600,  
  8.             modal: true,  
  9.             buttons: {  
  10.                 Close: function () {  
  11.                     $(this).dialog('close');  
  12.                 }  
  13.             }  
  14.         });  
  15.     }  
  16. </script>  
Then we are going to call the ZoomImage function on click of image as shown below.

Calling JavaScript function of ZoomImage on click of Image
  1. <img id="imagebtn"   
  2.       onclick="ZoomImage('data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))')"   
  3.       src="data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))"    
  4.       width="70px"   
  5.       height="70px"    
  6.       alt="@item.FileName" />  
After calling ZoomImage function on click of image we are going to add a div and give it a Unique ID. This div contains img tag inside it which display large image as we click on it.

Popup which is displayed when we click on image
  1. <div id="popupdiv" style="display: none">  
  2.   
  3.    <img id="main" src="images/main.jpg">  
  4. </div>  
After explaining part of code the snippet now I am going to show enter.

Code snippet of ShowImages.cshtml 
  1. @model List<WebGridwithImages.Models.FileTB>  
  2. @{  
  3.     ViewBag.Title = "Show Images";  
  4.     Layout = null;  
  5. }  
  6. <!DOCTYPE html>  
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <title>Show Images</title>  
  11.       
  12.     <link href="~/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet" />  
  13.     <script src="~/Scripts/jquery-1.9.1.js"></script>  
  14.     <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>  
  15.     <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />  
  16.     <script src="~/Scripts/jquery-1.8.2.js"></script>  
  17.     <script src="~/Scripts/jquery-ui-1.8.24.js"></script>  
  18.   
  19.     <script type="text/javascript">  
  20.         function ZoomImage(image) {  
  21.             document.getElementById("main").src = image;  
  22.             $("#popupdiv").dialog({  
  23.                 width: 600,  
  24.                 height: 600,  
  25.                 modal: true,  
  26.                 buttons: {  
  27.                     Close: function () {  
  28.                         $(this).dialog('close');  
  29.                     }  
  30.                 }  
  31.             });  
  32.         }  
  33.     </script>  
  34. </head>  
  35. <body>  
  36.     <div style="margin-left: 50px; margin-right: 50px; margin-top: 50px;">  
  37.         @{    
  38.             var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);  
  39.             grid.Pager(WebGridPagerModes.All);  
  40.         }  
  41.          @grid.GetHtml(  
  42.                htmlAttributes: new { id = "gridMapping" },  
  43.                tableStyle: "table table-bordered",  
  44.                headerStyle: "info",  
  45.                footerStyle: "info",  
  46.                alternatingRowStyle: "webgrid-alternating-row",  
  47.                selectedRowStyle: "webgrid-selected-row",  
  48.                rowStyle: "gridrow",  
  49.                columns: grid.Columns  
  50.                (  
  51.                grid.Column("FileName""FileName"null, style: "name"),  
  52.                grid.Column(header: "Images", format:   
  53.                @<text>  
  54.                  <img id="imagebtn"   
  55.                       onclick="ZoomImage('data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))')"   
  56.                       src="data:image/jpg;base64,@(Convert.ToBase64String(item.Filebytes))"    
  57.                       width="70px"   
  58.                       height="70px"    
  59.                       alt="@item.FileName" />  
  60.                </text>, style: "Imagepix"))  
  61.          )  
  62.     </div>  
  63.     <div id="popupdiv" style="display: none">  
  64.         <img id="main" src="images/main.jpg">  
  65.     </div>  
  66.   
  67. </body>  
  68. </html>  
Code snippet of Default1Controller
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using WebGridwithImages.Models;  
  8. namespace WebGridwithImages.Controllers  
  9. {  
  10.     public class Default1Controller: Controller  
  11.     {  
  12.         public ActionResult Index()  
  13.         {  
  14.             return View();  
  15.         }  
  16.         [HttpGet]  
  17.         public ActionResult UploadImages()  
  18.         {  
  19.             return View();  
  20.         }  
  21.         [HttpPost]  
  22.         public ActionResult UploadImages(HttpPostedFileBase uploadFile)  
  23.         {  
  24.             try  
  25.             {  
  26.                 OrderDB1Entities ODB = new OrderDB1Entities(); // DbContext  
  27.                 FileTB objfiletb = new FileTB(); // object of table  
  28.                 HttpPostedFileBase httpobj = Request.Files["file"];  
  29.                 string[] Filename = httpobj.FileName.Split('.'); //Spliting Image Name to Get FileName  
  30.                 objfiletb.FileID = 0;  
  31.                 objfiletb.FileName = Filename[0];  
  32.                 using(Stream inputStream = Request.Files[0].InputStream) //File Stream which is Uploaded  
  33.                 {  
  34.                     MemoryStream memoryStream = inputStream as MemoryStream;  
  35.                     if (memoryStream == null)  
  36.                     {  
  37.                         memoryStream = new MemoryStream();  
  38.                         inputStream.CopyTo(memoryStream);  
  39.                     }  
  40.                     objfiletb.Filebytes = memoryStream.ToArray();  
  41.                 }  
  42.                 ODB.FileTBs.Add(objfiletb);  
  43.                 ODB.SaveChanges(); //Inserting Image in Database  
  44.                 TempData["Message"] = "Data Saved Successfully";  
  45.                 return View();  
  46.             }  
  47.             catch (Exception)  
  48.             {  
  49.                 throw;  
  50.             }  
  51.         }     
  52.         [HttpGet]  
  53.         public ActionResult ShowImages()  
  54.         {  
  55.             OrderDB1Entities ODB = new OrderDB1Entities(); //DBcontext class   
  56.             var listofpic = ODB.FileTBs.ToList(); // Get List of images stored in FileTB table  
  57.             return View(listofpic);  
  58.         }  
  59.     }  
  60. }  
Save and Run Application

After completing with the code, save your application and run Access Action Method ShowImages().

Run Application

Enlarged image after clicking on image in WebGrid.

Enlarged image

Finally, we have completed displaying Binary data (Images) in WebGrid from the database that open in a popup when clicked.
 
Read more articles on WebGrid:

Up Next
    Ebook Download
    View all
    Learn
    View all