In this article I will explain with an example, how to display images stored in the
SQL Server database in ASP.Net MVC.
Database
I have made use of the following table tblFiles with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
Model
The Model class consists of the following properties. The additional property IsSelected is used for displaying the selected item in DropDownList after Form submission.
public class ImageModel
{
public int Id { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
public bool IsSelected { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, a Generic List collection of
ImageModel class is created and
GetImages method is called where the records from the
SQL Server database such as Id, Name, ContentType and Data (Binary data) of the image file are fetched.
Finally, a Generic List collection of ImageModel class object is returned to the View.
Action method for handling POST operation
Inside this Action method, a Generic List collection of
ImageModel class is created and
GetImages method is called where the records are fetched from the
SQL Server database.
Then, the Find method is called where we pass the Lambda expression and the image is determined.
A check is performed if the image is not NULL then the Binary data of the image i.e. the BYTE Array is converted to a
Base64 string and is assigned to the
Base64String ViewBag object.
Finally, a Generic List collection of ImageModel class object is returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<ImageModel> images = this.GetImages();
return View(images);
}
[HttpPost]
public ActionResult Index(int imageId)
{
List<ImageModel> images = this.GetImages();
ImageModel image = images.Find(p => p.Id == imageId);
if (image != null)
{
image.IsSelected = true;
ViewBag.Base64String = "data:image/png;base64," + Convert.ToBase64String(image.Data, 0, image.Data.Length);
}
return View(images);
}
private List<ImageModel> GetImages()
{
string sql = "SELECT Id, Name, ContentType, Data FROM tblFiles";
List<ImageModel> images = new List<ImageModel>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
images.Add(new ImageModel
{
Id = Convert.ToInt32(sdr["Id"]),
Name = sdr["Name"].ToString(),
ContentType = sdr["ContentType"].ToString(),
Data = (byte[])sdr["Data"]
});
}
}
con.Close();
}
}
return images;
}
}
View
HTML Markup
Inside the View, the ImageModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View also consists of an HTML SELECT DropDownList and an Image control.
The DropDownList has been assigned with the onchange event handler.
onchange – This event is triggered when selected value of DropDownList changes.
Then, a FOR EACH loop is executed and a check is performed if image is selected then it sets the selected attribute of the OPTION element of DropDownList.
Finally, the
ViewBag object is checked for NULL and if it is not NULL then the value of the
ViewBag object is set in the
src property of the
Image control.
@using Display_Image_Database_MVC.Models
@model IEnumerable<Display_Image_Database_MVC.Models.ImageModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<span>Select Image:</span>
<select name="ImageId" onchange="document.forms[0].submit();">
<option value="0">Please select</option>
@foreach (ImageModel image in Model)
{
if (image.IsSelected)
{
<option value="@image.Id" selected="selected">@image.Name</option>
}
else
{
<option value="@image.Id">@image.Name</option>
}
}
</select>
}
@if (ViewBag.Base64String != null)
{
<hr />
<img alt="" src="@ViewBag.Base64String" style="height:100px; width:100px;" />
}
</body>
</html>
Screenshot
Downloads