Monday 27 October 2014

How to Save Images with File and Show with WebGrid in MVC 4.0 Application

How to Save Images with File and Show with WebGrid in asp.net MVC4 Application………………..

Note: In this topic I will explain How to save image name in sql table and save images in  Image Folder after that how to show save  images  in WebGrid in Mvc 4.0

-- Sql Query.....................................

create  database test
use test
create table User_Image
(
SrNo int primary key,
Name varchar(50),
Photo varchar(max)
)
First we will open Visual Studio 2012 AFTER THAT following below steps
Step 1: File -> New Project -> ASP.NET MVC 4 Web Application
And select Internet Application with Razor View engine (as like below)


Step 2: After that we will add Model1.edmx and follow all steps with Models as always you doing it.

Step 3: Then we  add Controller which  name  is MyImage Controller you will get by defalt  Index Action ,

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
// using this  name  space  here.....
using WebGridWithImageMvc4.Models;

namespace WebGridWithImageMvc4.Controllers
{
public class MyImageController : Controller
{
//
// GET: /MyImage/

testEntities tt = new testEntities();
public ActionResult Index()
{

//In  you want to  show  image  in the  same  view as you  have saved the image you can do this  code
//List<User_Image> uimg = new List<User_Image>();
//uimg = tt.User_Image.OrderBy(m => m.SrNo).ToList();
//return View(uimg);
return View();
}
}
}

Step 4: using this Index we will create View Which Name is  Index   and  write code given bellow………


@model  List<WebGridWithImageMvc4.Models.User_Image>
@{
Layout = null;

}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>


<style type="text/css">
table
{
font-family: verdana,arial,sans-serif;
font-size: 11px;
color: #333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table th
{
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede;
}
table td
{
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
</style>
</head>
<body>

<div class="signup" id="new">
@using (Html.BeginForm("Index", "MyImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table width="100%" border="5px">
<tr><td colspan="2"><b><center><b><i>How to Save Image in DataBase and Show with WebGrid in Mvc 4.0</i></b></center></b></td></tr>

<tr><td>SrNo</td><td>@Html.TextBox("txtSrNo")</td></tr>
<tr><td>Name:</td><td>@Html.TextBox("txtName")</td></tr>
<tr><td>Profile Image:</td><td><input name="file" type="file" /></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" id="submit" value="Save Image" /></td></tr>
<tr><td colspan="2">

<div style="color:red;">@ViewData["error"]</div>

Show Data :  @Html.ActionLink("Show Image ","ShowImage","MyImage")

@if (ViewData["msg"] != null)
{
if (ViewData["msg"].ToString() == "1")
{
<div style="color:Green;">Registration Successful.</div>
}
else if (ViewData["msg"].ToString() == "2")
{
<div style="color:Orange;">Please upload only  jpg and jpge file for image.</div>
}
else
{
<div style="color:Red;">upload only less than and equal image with 12 kb.</div>
}
}
</table>
}
</div>
</body>
</html>

Step 5: Then we will go to same Controller MyImage and create same Index Action but action method is HttpPost...........


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
// using this  name  space  here.....
using WebGridWithImageMvc4.Models;

namespace WebGridWithImageMvc4.Controllers
{
public class MyImageController : Controller
{
//
// GET: /MyImage/

testEntities tt = new testEntities();
public ActionResult Index()
{
return View();
}

// code for how to save Image in DataBase…………………………

[HttpPost]
public ActionResult Index(FormCollection fc, HttpPostedFileBase file)
{
try
{

//In this code we  are working with file upload ,It must upload only jpg and jpeg format and size less than 12 kb
var allowedExtensions = new[] { ".jpg", ".jpeg",".png" };
var extension = Path.GetExtension(file.FileName);

if (file.ContentLength <= 12228)
{
if (allowedExtensions.Contains(extension))
{

var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/UserImages/"), filename);
file.SaveAs(path);
User_Image uu = new User_Image
{
SrNo = Convert.ToInt32(fc["txtSrNo"]),
Name = fc["txtName"].ToString(),
Photo = file.FileName
};
tt.User_Image.Add(uu);
tt.SaveChanges();
ViewData["msg"] = 1;
}
else
{
ViewData["msg"] = 2;// "Please upload only  jpg and jpge file for image";
}
}
else
{
ViewData["msg"] = 3;//"upload only 10 kb ";
}
}

catch (Exception ex)
{
ViewData["error"] = ex.Message;
}

return View();
//In  you want to  show  image  in the  same  view as you  have saved the image you can do this  code
//List<User_Image> uimg = new List<User_Image>();
//uimg = tt.User_Image.OrderBy(m => m.SrNo).ToList();
//return View(uimg);

}
}
}
Result:


Step 6: Again we will go to same Controller MyImage and create Action method which name is ShowImage like

public ActionResult ShowImage()

{

List<User_Image> uimg = new List<User_Image>();
uimg = tt.User_Image.OrderBy(m => m.SrNo).ToList();
return View(uimg);

}

Pictorial Representation of  Models Views And Controller …………………………..




Step 7: using above Action we add New View which name is ShowImage.cshtml with strongly typed view with Empty and write code like……

@model List<WebGridWithImageMvc4.Models.User_Image>

@{
Layout = null;
ViewBag.Title = "User with Image";
var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 10);
grid.Pager(WebGridPagerModes.All);
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowImage</title>

<style type="text/css">
table
{
font-family: verdana,arial,sans-serif;
font-size: 11px;
color: #333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table th
{
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede;
}
table td
{
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
</style>
</head>
<body>
<div>
<table>
<tr><td>Show All Image from DataBase</td></tr>
<tr><td>

@grid.GetHtml(
columns:grid.Columns
(
grid.Column(columnName:"SrNo",header:"SrNo"),
grid.Column(columnName:"Name",header:"Name"),

grid.Column(
format: (item) =>
{
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"UserImages\" width='75px' height='75px'/></text>","/UserImages/"+Url.Content(@item.Photo)));
}
)
))
</td></tr>
<tr><td>Go  to: @Html.ActionLink("Save Image Again ","Index","MyImage")</td></tr>
</table>

</div>
</body>
</html>

Result: 

0 comments:

Post a Comment