Friday, April 22, 2016

ASP.NET MVC: Dynamically display images in webgrid

In this article I am going to explain how to display images in asp.net mvc webgrid.


Implementation:
I have created a Table Employees and Insert some dummy data into it.

ASP.NET MVC:  Dynamically display images in webgrid

Add Controller
I have added an empty controller to project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;

namespace MVC_Project.Controllers
{
    public class EmployeeController : Controller
    {
        DemoEntities db = new DemoEntities();
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            return View(db.Employees1.ToList());
        }

    }
}

Add view

Right click on Index >> Add View >> Check the create a strongly-typed view >> Select the Model class and click on add button.

@model IEnumerable<MVC_Project.Models.Employee1>

@{
    WebGrid grid = new WebGrid(Model, canSort: true, canPage: true,rowsPerPage:5);
}
<style type="text/css">
    table {
        width: 80%;

    }

    th {
        padding: 2px 2px 2px;
    }

    td {
        text-align: center;
    }
</style>
@grid.GetHtml(
    tableStyle: "table",
    fillEmptyRows: true,
    headerStyle: "false",
    footerStyle: "false",
    mode: WebGridPagerModes.All,
    columns: new[]
    {
        //the model fields to display
        grid.Column("Name","Name"),
        grid.Column("Phone","Phone"),
        grid.Column("Salary","Salary"),
         grid.Column("Department","Department"),
        grid.Column(header:"Profile Image", format: @<text><img src="../@item.ImagePath" alt="Image" width="100px"/></text>),       
   }
 )



Result:
ASP.NET MVC:  Dynamically display images in webgrid

No comments:

Post a Comment