Display Data in GridView Using Asp.net MVC

In this article we have learn about,How to Display Data in Gridview using Asp.Net MVC using sql server database and visual studio,here we will bind data from sql to gridview control using Mvc razor view.

Step 1 : Open sql server database and create database table tbl_user

CREATE TABLE [dbo].[tbl_user] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[name] NVARCHAR (50) NOT NULL,
[city] NVARCHAR (50) NOT NULL,
[address] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

Step 2: Now Create Model class DAL.csBAL.cs

Model DAL.cs

public class DAL
{
public int id { get; set; }
public string name { get; set; }
public string city { get; set; }
public string address { get; set; }

}

Class BAL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace MvcGrid.Models
{
public class BAL
{
SqlConnection con = new SqlConnection(@”Data Source=(LocalDB)\v11.0;AttachDbFilename=
D:\Chetan_program\App_Data\Database1.mdf;Integrated Security=True“);
public List get()
{
List L = new List();
con.Open();
SqlCommand cmd = new SqlCommand(“select * from tbl_user”,con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DAL da = new DAL();
da.name = (dr[“name“]).ToString();
da.address = (dr[“address“]).ToString();
da.city = (dr[“city“]).ToString();
L.Add(da);}
con.Close();
return L;
}
}

Step 3: Now create controller ABCController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcGrid.Models;
namespace MvcGrid.Controllers
{
public class ABCController : Controller
{
BAL ba = new BAL();
public ActionResult Index()
{
return View();
}public ActionResult Grid()
{
DAL da = new DAL();
ba.get();
return View(ba.get());
}

Step 4 : Now add view for display gridview  Grid.cshtml 

@model List<MvcGrid.Models.DAL>

@{
ViewBag.Title = “Grid“;
}

<h2>Grid</h2>
@{

var Grid=new WebGrid(Model);
@Grid.GetHtml();

}

Step 5 :  Now, Run Web Application and see output

Display Data in GridView Using Asp.net MVC

SEE MORE

22 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *