Using DetailsView and GridView in ASP.NET MVC


Introduction : ASP.NET MVC makes use of the MVC design pattern and the result is far different at code level. ASP.NET MVC divides the entire processing logic into three distinct parts namely model, view and controller. In the process views (that represent UI under MVC architecture) needed to sacrifice three important features of web forms: Post backs, View State and rich event model. Let's quickly see why this sacrifice is necessary. Remember that in the following sections when I say "web form" I mean the original web form model and when I say "MVC web page" I mean MVC based web forms, though technically they belong to the same inheritance chain.

To illustrate how we can use ASP.NET server controls in an ASP.NET MVC web pages we will develop a sample application. In this application we will make use of the GridView and Details View controls. The application adds, edits, deletes and selects records from an Employees table.

Step 1:

  • Go to file -> New->Projects.
  • Open  ASP.NET MVC 2 Empty Web Application.

start.gif

Step 2:

  • Right click on the  App_Data Folder ->Add New Item ->SQL Server Database.
  • After attach a database. Right click of database and add a table name is "Employee".
  • The fields of these table "Id,Name,Salary".
  • Add some values in a table for testing purposes.

SQL.gif

tableschema.gif

TableRecords.gif

Step 3:

  • Then add a new LINQ to SQL Classes (.dbml) file to Models folder. Drag and drop Employees table onto its design surface from the Server Explorer. Doing so will create a LINQ to SQL class (Employee) for Employees table. This class will form the model for our MVC pages.
  • Right click of  Model  Folder -> Add ->Add New Items-> Add  LINQ to SQL Classes (.dbml).

linqqq.gif

Step 4 :

  • Right Click of View Folder->Add a files.
  • Name is "Index".

    index.gif

gridview.gif

temlatefield.gif

Code :

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = ViewData["emplist"];
        GridView1.DataBind();
    }
</script>
<
html>
<
head>
<
title>
</
title>
</
head>
<
body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" EnableModelValidation="True">
        <Columns>
            <asp:HyperLinkField HeaderText="Edit" DataNavigateUrlFields="Id"
    DataNavigateUrlFormatString="~/Employee/ShowUpdateView/{0}"
    Text="Edit" ></asp:HyperLinkField>
            <asp:HyperLinkField DataNavigateUrlFields="Id"
    DataNavigateUrlFormatString="~/Employee/Delete/{0}"
    Text="Delete"
>
</asp:HyperLinkField>
            <asp:TemplateField HeaderText="Id">
            <ItemTemplate>
        <asp:Label ID="Label1" runat="server"
        Text='<%# Bind("Id") %>'></asp:Label>
    </ItemTemplate></asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
        <asp:Label ID="Label1" runat="server"
        Text='<%# Bind("Name") %>'></asp:Label>
    </ItemTemplate></asp:TemplateField>
        </Columns>
     </asp:GridView>
    <div>
    </div>
    </form
>
</body></html>

Step 5 :

  • Right click on the Controllers Folder -> add Controllers name as "EmployeeControllers".

trolew.gif

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication6.Models;
namespace MvcApplication6.Controllers
{
    public class EmployeeController : Controller
    {
     public ActionResult Index()
        {
            DataClasses1DataContext db = new DataClasses1DataContext();
            IQueryable<Employee> emplist = from rows in db.Employees select rows;
            ViewData["emplist"] = emplist;
            return View();
        }
        public ActionResult ShowInsertView()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Insert(FormCollection collection)
        {
            DataClasses1DataContext db = new DataClasses1DataContext();
            Employee item = new Employee();
            item.Name = collection["DetailsView1$txtName"];
            item.Notes = collection["DetailsView1$txtNotes"];
            db.Employees.InsertOnSubmit(item);
            db.SubmitChanges();
            return RedirectToAction("Index");
        }
        public ActionResult ShowUpdateView(int id)

        {
            DataClasses1DataContext db = new DataClasses1DataContext();
            var temp = from item in db.Employees
                       where item.Id == id
                       select item;
            ViewData["emplist"] = temp.ToList();
            return View();
        }
        [HttpPost]
        public ActionResult Update(int id, FormCollection collection)
        {
            DataClasses1DataContext db = new DataClasses1DataContext();
            var temp = from item in db.Employee where item.Id == id select item;
            temp.First().Name = collection["DetailsView1$txtName"];
            temp.First().Notes = collection["DetailsView1$txtNotes"];
            db.SubmitChanges();
            return RedirectToAction("Index");
        }
        public ActionResult Delete(int id)
        {
            DataClasses1DataContext db = new DataClasses1DataContext();
            var temp = from item in db.Employees where item.Id == id select item;
            db.Employees.DeleteOnSubmit(temp.First());
            db.SubmitChanges();
            return RedirectToAction("Index");
        }
    }
}

Step 5 : 

  • Right Click of View Folder->Add Two files.

  • First Name is "ShowInsertView.aspx".

insert-view.gif

Code :

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        object emplist = ViewData["emplist"];
        DetailsView1.DataSource = emplist;
        DetailsView1.DataBind();
    }
</script>
<
html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ShowInsertView</title
>
</head>
<
body>
    <form id="form1" runat="server">
    <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"
        DataSourceID="SqlDataSource1" EnableModelValidation="True">
    <Fields>
     <asp:TemplateField HeaderText="Name :">
         <InsertItemTemplate>
           <asp:TextBox ID="txtName" runat="server"
             Text='<%# Bind("Name") %>' />
         </InsertItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField HeaderText="Notes :">
        <InsertItemTemplate>
           <asp:TextBox ID="txtNotes" runat="server"
             Text='<%# Bind("Notes") %>' Rows="3"
             TextMode="MultiLine"></asp:TextBox>
        </InsertItemTemplate>
    </asp:TemplateField>
    </Fields>
    <FooterTemplate>
     <asp:Button ID="Button1" runat="server"
       PostBackUrl="~/Employee/Insert"
       Text="Save" Width="75px" />
    </FooterTemplate>
    </asp:DetailsView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:Database1ConnectionString %>"
        SelectCommand="SELECT [Id], [Name], [Notes] FROM [Employees]">
    </asp:SqlDataSource>
    <div>
    </div>
    </form
>
</body>
</
html>

Step 6:

  • Second is "ShowUpdateView.aspx". 

update-inage.gif

Code :

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ShowUpdateView</title
>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
        <asp:DetailsView ID="DetailsView1" runat="server" DefaultMode="Edit" Height="50px" Width="125px">
        <Fields>
        <asp:TemplateField HeaderText="Id :">
            <EditItemTemplate>
                <asp:Label ID="Label1" runat="server"
                 Text='<%# Bind("Id") %>'></asp:Label>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name :">
            <EditItemTemplate>
                <asp:TextBox ID="txtName" runat="server"
                  Text='<%# Bind("Name") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Notes :">
            <EditItemTemplate>
                <asp:TextBox ID="txtNotes" runat="server"
                  Text='<%# Bind("Notes") %>' Rows="3"
                  TextMode="MultiLine"></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
    </Fields>
    <FooterTemplate>
        <asp:Button ID="Button1" runat="server"
            PostBackUrl='<%# Eval("Id","~/Employee/Update/{0}") %>'
            Text="Save" Width="75px" />
    </FooterTemplate>
</
asp:DetailsView>
    </div>
    </form
>
</body></html>

Output :

  • Press f5 and see the output.

 output.gif

Up Next
    Ebook Download
    View all
    Learn
    View all