Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Create Image (Photo) Gallery in Asp.net MVC in jQuery using C#

Dec 17, 2014
Introduction:

Here I will explain how to create image or photo gallery in Asp.net MVC in jQuery using c# or how to upload and display images in asp.net MVC using jQuery in c#.

Description:

In previous posts I explained mvc tutorial with Razor for beginners, create a form and insert data into database in mvc, show data from datatable in mvc and many more articles related to asp.net MVC, asp.net, jQuery, c#. Now I will explain how to create dynamic image gallery in asp.net MVC in jQuery using c#.

The user uploads multiple images at once and those images will be added to a photo gallery or album. As part of uploading image process, we need to store original images on website’s uploads folder. At the same time, we also need to create thumbnail of images. We can divide complete functionality in below 2 processes:

1) User uploads multiples images to create a new photo gallery. Store gallery details into database.

2) Display uploaded images.

First of all create table tblGallery into database to implement slideshow functionality as shown below

Column Name
Data Type
Allow Nulls
ImageId
Int(Set Identity Property = true)
Not Null
ImageName
Varchar(50)
Null
Photo
Varbinary(max)
Null

After creating Database Table, create an ASP.NET MVC Application as project. As shown below as figure


Now create an AlbumMaster Class by right click on the Models folder as add a New Item


public class AlbumMaster
{
public int ImageId { get; set; }
public string ImageName { get; set; }
public byte[] Image { get; set; }
}
Now create an AlbumModelService Class by right click on the Models folder as add a New Item for doing ado.net database operation for photo gallery


namespace MVChero.Models
{
public class AlbumModelService
{
}
}
Now create a controller Employee by Right click on the controller folder and select add as controller


Now right click on the ActionResult method in the controller, to create a View for photo gallery application.

Create view as Create as a strong typed view and choose AlbumMaster model class from list. It is shown as below as figure. If AlbumMaster model class is not in the list, then you should build the application. Then do the above process


First of all we will create a form to Upload Image. Go to View Index and then add these statement


@model IList<MVChero.Models.AlbumMaster>
@{
ViewBag.Title = "Index";
int i = 0;
}
<script type="text/javascript">
function ValidateForm() {
var txt1 = document.getElementById('ImageName');
if (txt1.value == '') {
alert("Enter Image Name !")
document.getElementById("ImageName").focus();
return false;
}
var uploadfile = document.getElementById('ImageData');

if (uploadfile.value == '') {
alert('Please upload the attachment');
uploadfile.focus();
return false;
}
var fname = uploadfile.value;
var ext = fname.split(".");
var x = ext.length;
var extstr = ext[x - 1].toLowerCase();
if (extstr == 'jpg' || extstr == 'jpeg' || extstr == 'png' || extstr == 'gif') { }
else {
alert("Please upload valid image");
uploadfile.focus();
return false;
}
}
</script>

<h2>Manage Albums</h2>
<div style="width:600px;">
@using (Html.BeginForm("Create", "ManageAlbums", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Create Albums</legend>
<table>
<tr>
<td>Album Name :</td>
<td>@Html.TextBox("ImageName", "", new { style = "width:200px" })</td>
</tr>
<tr>
<td>Image : </td>
<td><input type="file" name="ImageData" id="ImageData" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Upload" onclick="return ValidateForm()" />
</td>
</tr>
</table>
</fieldset>
}
</div>
Our form should be like as shown below


Now add the codes to the AlbumMasterModel class for uploading images into database


SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ToString());
public int UploadAlbums(AlbumMaster objAlbumMaster)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "INSERT INTO tblGallery(ImageName,Photo) VALUES(@ImageName,@Photo)";
scmd.Parameters.AddWithValue("@ImageName", objAlbumMaster.ImageName);
scmd.Parameters.AddWithValue("@Photo", objAlbumMaster.Image);
scon.Open();
int status = scmd.ExecuteNonQuery();
scon.Close();
return status;
}
}
To post form data, we need to add HttpPost action method for Index controller. So add a new action method of HttpPost of Index in controller


[HttpPost]
public ActionResult Index(FormCollection collection)
{
HttpPostedFileBase file = Request.Files["ImageData"];
AlbumMaster objAlbumMaster = new AlbumMaster();
objAlbumMaster.ImageName = collection["ImageName"].ToString();
objAlbumMaster.Image = ConvertToBytes(file);
objAlbumModelService.UploadAlbums(objAlbumMaster);
return View(objAlbumModelService.GetAlbums().ToList());
}
To Display Image Albums add these lines of code to AlbumModelService class to retrieve image from database


public IList<AlbumMaster> GetAlbums()
{
List<AlbumMaster> objAlbumList = new List<AlbumMaster>();
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM tblGallery";
scon.Open();
SqlDataReader sdr = scmd.ExecuteReader();
while(sdr.Read())
{
AlbumMaster objAlbumMaster = new AlbumMaster();
objAlbumMaster.ImageId = Convert.ToInt32(sdr["ImageId"]);
objAlbumMaster.ImageName = sdr["ImageName"].ToString();
objAlbumMaster.Image = (byte[])sdr["Photo"];
objAlbumList.Add(objAlbumMaster);
}

if(sdr != null)
{
sdr.Dispose();
sdr.Close();
}
scon.Close();
return objAlbumList.ToList(); ;
}
}

public byte[] GetImageFromDataBase(int id)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT Photo FROM tblGallery where ImageId=@ImageId";
scmd.Parameters.AddWithValue("@ImageId", id);
scon.Open();
SqlDataReader sdr = scmd.ExecuteReader();
AlbumMaster objAlbum = new AlbumMaster();
while(sdr.Read())
{
objAlbum.Image = (byte[])sdr["Photo"];
}
return objAlbum.Image;
}
}
Now we need to call this method in controller action method, to get the data from model and pass this data to view for displaying images.

Add these lines to controller Index action method


public ActionResult Index()
{
ViewBag.total = objAlbumModelService.GetAlbums().ToList().Count;
return View(objAlbumModelService.GetAlbums().ToList());
}
Add these methods to convert byte array into image format


public byte[] ConvertToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}

public ActionResult RetrieveImage(int id)
{
byte[] cover = objAlbumModelService.GetImageFromDataBase(id);
if (cover != null)
{
return File(cover, "image/jpg");
}
else
{
return null;
}
}
Now add some lines of code to View, for displaying the images in a Tabular format with CSS


<h2>
Photo Gallery</h2>
<table cellpadding="5" cellspacing="5" width="440">
@{
//repeatdirection = Horizontal, RepeatColumns = 4
const int NumberOfColumns = 4;
int skip = 0;
var items = Model.Skip(skip).Take(NumberOfColumns);
while (items.Count() > 0)
{
<tr>
@foreach (var item in items)
{
<td width="450">
<table class="thumbmain">
<tr>
<td>
<img src="/ManageAlbums/RetrieveImage/@item.ImageId" width="120" height="120" class="imageclass" />
</td>
</tr>
<tr>
<td style="text-align: center; font-weight: bold; color: Teal">@item.ImageName
</td>
</tr>
</table>
</td>
}
</tr>
skip += NumberOfColumns;
items = Model.Skip(skip).Take(NumberOfColumns);
}
}
</table>
Now, I am going to upload some images and the images are displayed like this manner, as below


Full code of ManageAlbums Controller is shows as below


public class ManageAlbumsController : Controller
{
AlbumModelService objAlbumModelService = new AlbumModelService();

[HttpGet]
[OutputCache(Duration = 60, VaryByParam = "None")]
public ActionResult Index()
{
ViewBag.total = objAlbumModelService.GetAlbums().ToList().Count;
return View(objAlbumModelService.GetAlbums().ToList());
}

[HttpPost]
public ActionResult Index(FormCollection collection)
{
HttpPostedFileBase file = Request.Files["ImageData"];
AlbumMaster objAlbumMaster = new AlbumMaster();
objAlbumMaster.ImageName = collection["ImageName"].ToString();
objAlbumMaster.Image = ConvertToBytes(file);
objAlbumModelService.UploadAlbums(objAlbumMaster);
return View(objAlbumModelService.GetAlbums().ToList());
}

public byte[] ConvertToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}

public ActionResult RetrieveImage(int id)
{
byte[] cover = objAlbumModelService.GetImageFromDataBase(id);
if (cover != null)
{
return File(cover, "image/jpg");
}
else
{
return null;
}
}
}
Now try to run your application and check output that would be like as shown below

Demo

Create Image (Photo) Gallery in Asp.net MVC in jQuery using C#

Download Attached Sample Code




If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

9 comments :

Anonymous said...

Great Work SIr.I got lot's of valuable things from this website .

Unknown said...

its nice..

Badri said...

First time i saw, how to upload and display images from database in Asp.net MVC, thanks a lot for this article..

ram said...

Super sir

Anonymous said...

Not a good one:
-your code is very bad organised.
-you use bad techniques to interact with the database. Why not Entity Framework?
-where is Model Binding? "FormCollection" is old.
-you specified in the title that you'll use jQuery. I can see just that long function: getElementById("id");
-Validation with if(textbox.value != "") alert("Wrong"!); it's also an old technique. Why not Model Validation?

It would be nice if you'd rewrite this article, using CRUD operations with EF with latest techniques. :)

Anonymous said...

Question: What's that Skip(); function in your Index.cshtml view in that razor code block? My compiler doesn't recognize it. Can you explain please?

Raj said...
This comment has been removed by the author.
Raj said...

hai Sir
I have an Error like

////Displayed Error
const int NumberOfColumns = 4;
int skip = 0;
//in Red Colour
var items = Model.Skip(skip).Take(NumberOfColumns);
//
while (items.Count() > 0)
{
////

what is the skip and where it is
Please Tell me Sir

hari said...

can you please sent code to my mail hari.krpt9@gmail.com

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.