How to upload and display image using Webgrid MVC C#

In this article you will learn
  1. How to upload image in MVC using C#?
  2. How to list image and data in Webgrid?

Output

If you are looking for an article on how to upload and view image in WebGrid, then this article might be best choice for you. Here, I am going to upload and list image in WebGrid using very simple techniques.

Steps:

  1. Create a New Project
  2. Create Database, Table and Image Folder
  3. Add ADO.NET Entity Data Model
  4. Add a Controller
  5. Add a View
  6. Run the Project

Step 1: Create a New Project

Here, I am creating a project with the name Upload_Image.

  1. Open Visual Studio.
  2. Go to File > New > Project
  3. Select Visual C# in left pane and then select ASP.NET Web Application.
  4. Give Project Name Upload_Image and click OK.
  5. Select MVC in Template Window and set Authentication type: No Authentication. Click OK.

Step 2: Create Database, Table and upload Folder

In this part we will create a Database, a Table and a folder “upload” in Project folder. This Image folder will keep the uploaded image.


Create Database: Upload_Image_DB
  1. Open Server Explorer by pressing CTRL + W or go to View > Server Explorer.
  2. Right click on Data Connections and select Create New SQL Server Database.
  3. Select your Server and then give Database Name as Upload_Image_DB. Click OK.

Create Table: Image_Table
  1. Expand Upload_Image_DB in Solution Explorer and Right click on Table. Select Add New Table.
  2. Create a Table "Image_Table" as follows:

Script

CREATE TABLE [dbo].[Image_Table]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [Title] NVARCHAR(200) NULL, 
    [Image] NVARCHAR(MAX) NULL
)
create database and table
  1. You must set auto increment for Id field. Right click on Id column and select Properties.
auto increment
  1. In the Properties, Expand Identity Specification and then select (Is Identity) to True.
Create Folder: upload
  1. Go to Solution Explorer and Right click on Project Name > Add > New Folder.
  2. Set folder name as upload

Step 3: Add ADO.NET Entity Data Model

Now, we will add ADO.NET Entity Data Model. This model will create entity classes for database table and will give us a visual diagram of tables and relationship. This data model handles most of the configuration automatically and gives us easy way to work with database table.

  1. Go to Solution Explorer > Right click on Project > Add New Item.
  2. Select Data in Left Pane and then Select ADO.NET Entity Data Model. Give model name as: ImageTableModel. Click on Add.
  3. EF Designer
  4. Select EF Designer from Database in next wizard and click Next.
  5. EF Designer
  6. In the next Window, click on New Connection button and then select your server and database. Give connection name as Upload_Image_Constring and then click Next.
  7. EF Designer
  8. In the next window, Select Table and then click on Finish button.
  9. EF Designer
  10. You will see that Table diagram is created.
  11. EF Designer

Step 4: Add a Controller

Till now, you have successfully created Database, Table and Entity Model. Now, this time to create an Action Method in HomeController and use entity data model to save, upload and retrieve image.

  1. Open HomeController.cs
  2. Add following code in it.
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace Upload_Image.Controllers
{
    public class HomeController : Controller
    {
        // This method will list the table' row
        [HttpGet]
        public ActionResult Index()
        {
            Upload_Image_ConString connection = new Upload_Image_ConString();
            return View(connection.Image_Table.ToList());
        }

        // This method will upload the image and data to the folder and database
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            //Getting File Details
            string name = Path.GetFileName(file.FileName);
            string path = "~/upload/" + name;

            //Saving file to Folder
            file.SaveAs(Server.MapPath(path));

            //Saving data to database
            Upload_Image_ConString connection = new Upload_Image_ConString();
            connection.Image_Table.Add(new Image_Table
            {
                Title = name,
                Image = path
            });
            connection.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Step 5: Adding View

After editing HomeController, you need to add FileUploader control in razor.

  1. Open Views > Home > Index.cshtml from solution explorer.
  2. Paste the following code.
@model IEnumerable<Upload_Image.Image_Table>
@{
    ViewBag.Title = "Home Page";
    WebGrid webGrid = new WebGrid(source: Model, canSort: false, canPage: false);
}


<div class="row">
    
    <div class="col-md-4">
        <h2>Upload Image</h2>
        <p>
           @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
           {
            <input type="file" name="postedFile" />
            <input type="submit" id="btnUpload" value="Upload" />
           }
        <hr />
        </p>        
    </div>
    
    <div class="col-md-4">
        <h2>List Image</h2>
        <p>
            @webGrid.GetHtml(
       htmlAttributes: new { @id = "WebGrid" },
       columns: webGrid.Columns(
           webGrid.Column("Id", "ID"),
           webGrid.Column("Title", "NAME"),
           webGrid.Column("Image", "PHOTO", format:@<text><img alt="@item.Title" src="@Url.Content(item.Image)" style="width:200px; height:auto; padding:30px;" /></text>)))
        </p>
    </div>
    
</div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/start/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>

Step 6: Run the Project

Press F5 to run the Project.

Output

Summary

In this article, I explained how can you upload image in MVC C# and list them in WebGrid.

 

Share your thought