Description:
Model:
In
this example we explain that how to display Image from Database in Asp.Net MVC.
Or how to bind Image from database in MVC Razor View. Generally we are
displaying image from folder as per fetching path from database here we stored
whole image in Database in Binary format and bind it in Asp.Net MVC Razor View.
public class PictureModel
{
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; }
}
Controller:
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<PictureModel> images = GetPictures();
return View(images);
}
[HttpPost]
public ActionResult Index(int imageId)
{
List<PictureModel> images = GetPictures();
PictureModel 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<PictureModel>
GetPictures()
{
string query = "SELECT * FROM tblFiles";
List<PictureModel> images = new List<PictureModel>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
images.Add(new PictureModel
{
Id = Convert.ToInt32(sdr["Id"]),
Name
= sdr["Name"].ToString(),
ContentType = sdr["ContentType"].ToString(),
Data = (byte[])sdr["Data"]
});
}
}
con.Close();
}
return images;
}
}
}
View:
@using Display_Image_Database_MVC.Models
@model IEnumerable<Display_Image_Database_MVC.Models.PictureModel>
@{
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 (PictureModel 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>
0 comments:
Post a Comment