Save images in database and display it into views using MVC

Introduction

In this article, I will show you how to upload multiple images and show them in the table Using MVC and entity framework. I am using visual studio 2012 framework and SQL server 2008 R2 for this demo.

So, before opening visual studio let’s create table tblStudent using following script.

Student table script

CREATE TABLE tblStudent
(
    StudentId INT NOT NULL PRIMARY KEY IDENTITY, 
    FirstName NVARCHAR(50) NULL, 
    LastName NVARCHAR(50) NULL, 
    ImageUrl NVARCHAR(50) NULL
)

Let’s start for this demo step by step using Asp.Net MVC 4 Web Application.

Step 1: Create MVC project, by using following steps.

  • Open Visual Studio.
  • Click on File -> New -> Project.
  • In this project, I am using C# as a programming language, but you can also choose VISUAL BASIC if you know the syntaxes of VB.
  • Inside Visual C# -> Web -> Select Asp.Net MVC 3, 4 or 5 -> Select Ok.

  • Now one more dialog box would open -> select Empty as a project template. -> OK.

Step 2 : After creating MVC project, you will find list of your project files inside ‘solution explorer’ on your right hand side.

  • Right click on your project name -> click add -> click New Folder -> rename that new folder to ‘Images’.

Step 3 : Create an ADO.NET Entity Data Model

  • Right click on your project -> Add -> New Item.

  • Search for Ado.Net entity data model inside search box. -> Name it as ‘StudentDataModel’ -> Click Add.

  • Inside entity data model wizard -> Select generate from database -> Click next.

  • Now from ‘New connection’ button -> Select data source -> ‘Microsoft SQL server’ -> Click continue.

  • Now select your database (. stands for localhost) name and select database ‘Sample’ -> Click OK

  • Now inside ‘Entity Data Model Wizard’ name your web.config file as StudentEntities -> Click next

  • Now select table(tblStudent) -> name model namespaces as StudentModel -> Click Finish

  • Now you will see Ado.Net Entity Data Model (StudentDataModel) added to your project’s files.

Step 4 : Add new controller

  • Right click on controller folder. Name your controller -> HomeController -> Click on Add button.
  • Now your controller would look something like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ImageuploadingDemo.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

    }
}
  • Now add following two methods inside your Home controller
public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file != null)
            {
                StudentEntities db = new StudentEntities();
                string ImageName = System.IO.Path.GetFileName(file.FileName);
                string physicalPath = Server.MapPath("~/Images/" + ImageName);
                file.SaveAs(physicalPath);
                tblStudent student = new tblStudent();
                student.FirstName = Request.Form["firstname"];
                student.LastName = Request.Form["lastname"];
                student.ImageUrl = ImageName;
                db.tblStudents.Add(student);
                db.SaveChanges();

            }
            return RedirectToAction("../home/DisplayImage/");
        }
public ActionResult DisplayImage()
       {
           return View();
       }

Step 5 : Add view

  • Now right click on index method -> Add index view

  • Add follwing code inside index view.

 

@{
   ViewBag.Title = "Index";
}
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
                    new { enctype = "multipart/form-data" }))
{
    <div>    
            
<h1>Add student information</h1>
First Name : @Html.TextBox("firstname") <br /><br /> 

Last Name :  @Html.TextBox("lastname") <br /><br />

Image : <input type="file" name="file" id="file" style="width: 100%;" /> <br /><br />

<input type="submit" value="Upload student info"/>
</div>    
}
  • Now add DisplayImage view and add follwing code.
@using ImageuploadingDemo;
@{
    ViewBag.Title = "DisplayImage";
}
@{   
   StudentEntities db = new StudentEntities();
}
<h1>Student Details</h1>
@using (Html.BeginForm())
{
<table border="1">
<thead>
    <tr>
        <th>Image</th>
        <th>First name</th>
        <th>Last name</th>
    </tr>
</thead>
<tbody>
   @foreach (var item in db.tblStudents)
    {
        <tr>
            <td><img src="~/images/@item.ImageUrl" width="100" height="100" /></td>
            <td>@item.FirstName</td>
            <td>@item.LastName</td>
        </tr>
    }
</tbody>
</table>
}

Step 6 : Result

Leave a Comment