Saturday, 7 March 2015

UPLOADING AND DISPLAYING IMAGES USING MVC

Data Base Design


File->New->Project



select : ASP.NET MVC 4- Application
AND CLICK ON OK


And select the project template and click on ok



And Go to Controller Folder and Right Click  AddController.




Next go to Model Folder and Add New Item.




Write the following Code in Employee.cs


public class Employee
    {
        public int UserId { get; set; }

        [Required(ErrorMessage = "FirstName is Required")]
        public string FirstName { get; set; }
        
        [Required(ErrorMessage = "Last Name is Required")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Salary is Required")]
        public int Salary { get; set; }

        public string ImageType { get; set; }

        public byte[] ImageLength { get; set; }
      
        public HttpPostedFileBase Image { get; set; }

        public List<Employee> GetAllEmployees()
        {
            DataTable objTbl = new DataTable();
            List<Employee> employeeList = new System.Collections.Generic.List<Employee>();
            SqlConnection objCon = new SqlConnection();
            objCon.ConnectionString = "Data source=abc;User Id=123;Password=123t; Initial Catalog=testing;Connection Timeout=30;";
            SqlDataAdapter objAdp = new SqlDataAdapter("select * from EmpImg", objCon);
            objAdp.Fill(objTbl);
            foreach (DataRow dr in objTbl.Rows)
            {
                employeeList.Add(new Employee()
                {
                    UserId = Convert.ToInt32(dr["UserId"]),
                    FirstName = Convert.ToString(dr["FirstName"]),
                    LastName = Convert.ToString(dr["LastName"]),
                    Salary = Convert.ToInt32(dr["Salary"]),
                });
            }
            return employeeList;
        }

    }










Now, Go to Employee Controller and write the following Code:












        public ActionResult Index()
        {
            Employee obj = new Employee();
            
            return View(obj.GetAllEmployees());
        }

        public ActionResult Create()
        {
            return View();
        }

        public ActionResult RetrieveImage(int id)
        {
            byte[] cover = GetImage(id);
            if (cover != null)
            {
                return File(cover, "image/jpg");
            }
            else
            {
                return null;
            }
        }

        public byte[] GetImage(int Id)
        {
            SqlConnection objCon = new SqlConnection();
            objCon.ConnectionString = "------------------";
            objCon.Open();
            System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("select Image from EmpImg where UserId=" + Id, objCon);
            System.Data.SqlClient.SqlDataReader dr = command.ExecuteReader();
            dr.Read();
            byte[] cover = (Byte[])dr[0];
            return cover;
        }
       
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Employee imageViewModel)
        {
            imageViewModel.ImageType = imageViewModel.Image.ContentType;
            imageViewModel.ImageLength = new byte[imageViewModel.Image.ContentLength];
            Int32 length1 = imageViewModel.Image.ContentLength;
            byte[] tempImage = new byte[length1];
            Stream fileStream = imageViewModel.Image.InputStream;
            fileStream.Read(tempImage, 0, length1);

            SqlConnection con = new SqlConnection();
            con.ConnectionString = "-------------";
            SqlCommand cmd = new SqlCommand();
            con.Open();
            cmd.Parameters.AddWithValue("@FirstName", Convert.ToString(imageViewModel.FirstName));
            cmd.Parameters.AddWithValue("@LastName", Convert.ToString(imageViewModel.LastName));
            cmd.Parameters.AddWithValue("@Salary", Convert.ToInt32(imageViewModel.Salary));
            cmd.Parameters.AddWithValue("@ImageType", Convert.ToString(imageViewModel.ImageType));
            cmd.Parameters.Add("@Image", SqlDbType.Binary).Value = tempImage;
            
            cmd.Connection = con;
            cmd.CommandText = "insert into EmpImg(FirstName,LastName,Salary,ImageType,Image)values(@FirstName,@LastName,@Salary,@ImageType,@Image)";
            cmd.ExecuteNonQuery();
            con.Close();
            return RedirectToAction("Index");

        }


Now,  Right Click on Index Method and select  Add View:



  


then the Index view is created in the views Folder as shown below.




Index.cshtml





@model IEnumerable<MvcApplication2.Models.Employee>
@{
    ViewBag.Title = "Index";
}
@{
    ViewBag.Title = "Index";
}
<p>
    @Html.ActionLink("Create New Employee", "Create",null, new { @class="btn btn-primary"})
</p>
<h2>Employee Details</h2>
<table class="table" style="width: 1000px;">
    <tr>
        <th> <b>FirstName</b> </th>
        <th> <b>Last Name</b> </th>
        <th> <b>Salary</b> </th>
        <th><b>Image</b></th>
    </tr>
     @foreach (var item in Model)
    {
        <tr>
            <td> @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td> @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>  @Html.DisplayFor(modelItem => item.Salary)
            </td>
            <td style="width: 500px;">
                <img src="/Employee/RetrieveImage/@item.UserId" alt="" height=100 width=200 />
            </td>
        </tr>

    }


And again go to Employee Controller, and Now right click on Create Method.






Create.cshtml


@model MvcApplication2.Models.Employee
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Employee", FormMethod.Post, new { enctype = "multipart/form-data" })) 

    @Html.ValidationSummary(true)
    <div class="form-group">
        @Html.LabelFor(model => model.FirstName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.LastName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.LastName, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Salary, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.Salary, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Salary)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Image, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="Image" />
        @Html.ValidationMessageFor(model => model.Image)
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
}
@section Scripts 
{
    @Scripts.Render("~/bundles/jqueryval")

}







Output:




http://localhost:54538/Employee/Create




No comments:

Post a Comment