DropDownList in GridView Async and find Control in Class File in c#.net


In this article, I have described the ways of keeping DropDownList in the GridView and binding the data by preserving the default SelectedValue. Apart from DropDownList, I have also shown how to keep CheckBox, RadioButtonList, TextBox in the GridView and preserving the default data,how to find control in class file ,how to use async Trigger in Update Panel using GridView in C#.net

Placing the DropDownList in the GridView

To place the DropDownList in the GridView, you will have to use asp:TemplateField that under <Columns>, Generally you will need to use the DropDownList in the GridView in the Edit mode (under EditItemTemplate, However this solution will work for you even if you want to place the DropDownList in the ItemTemplate) where you want your user to select the data from the DropDownList and update the record. A typical example is shown in the picture below

Image

The aspx page code of above GridView is below

<%@ Page Title="" Language="C#" MasterPageFile="~/GridMaster.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="Default" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"
    ClientIDMode="Static">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" ClientIDMode="Static">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="GridView1" />
        </Triggers>
        <ContentTemplate>
            <asp:Label ID="lblMessage" runat="server" EnableViewState="true" />
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ClientIDMode="Static"
                GridLines="None" AutoGenerateEditButton="True" OnRowCancelingEdit="GridViewCancelEdit"
                OnRowEditing="GridViewEdit" OnRowUpdating="GridViewUpdate" 
                DataKeyNames="PersonID" CellPadding="4" ForeColor="#333333">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField DataField="PersonID" HeaderText="Person ID" ReadOnly="True" Visible="false" />
                    <asp:TemplateField HeaderText="First Name">
                        <ItemTemplate>
                            <%# Eval("FName") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FName") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Last Name">
                        <ItemTemplate>
                            <%# Eval("LName") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LName") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Department DropDown">
                        <ItemTemplate>
                            <%# Eval("DeptName")%>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="dropDownDept" DataSource="<%# BindDropDownDepartment() %>"
                                DataTextField="DeptName" DataValueField="DeptId" runat="server" SelectedValue='<%# Eval("DeptId").ToString() %>'>
                            </asp:DropDownList>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="CustomCheckBox Field">
                        <ItemTemplate>
                            <%# Eval("IsActive") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("IsActive") %>' />
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="RadioButtonField">
                        <ItemTemplate>
                            <%# Eval("IsActive") %>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:RadioButtonList ID="radioActive" runat="server" RepeatDirection="Horizontal"
                                RepeatLayout="Flow" SelectedValue='<%# Eval("IsActive") %>'>
                                <asp:ListItem Text="True" Value="True" />
                                <asp:ListItem Text="False" Value="False" />
                            </asp:RadioButtonList>
                        </EditItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

In your code behind file of Default.aspx.cs code will be such as below given

using System;
using System.Data;
 
public partial class Default : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var obj = new BAL();
            obj.LoadPerson(ref  GridView1);
        }
    }
    
    protected DataTable BindDropDownDepartment()
    {
        var obj = new BAL();
        return obj.LoadAll();
    }
    protected void GridViewCancelEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
    {
        var obj = new BAL();
        GridView1.EditIndex =-1;
        obj.LoadPerson(ref  GridView1);
 
    }
    protected void GridViewEdit(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
    {
        var obj = new BAL();
        GridView1.EditIndex = e.NewEditIndex;
        obj.LoadPerson(ref  GridView1);
 
    }
    protected void GridViewUpdate(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
    {
        
        GridView1.EditIndex = -1;
        var obj = new BAL();
        obj.UpdateGrid(ref GridView1, e.RowIndex);
    }
}

Now Add a class File in Your Application and write down in that below given code.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
 
/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
 
    public BAL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public void LoadPerson(ref GridView grd)
    {
 
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var objAdp = new SqlDataAdapter("usp_PersonRecords", objCon))
            {
                objAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
                var ds = new DataSet();
                objAdp.Fill(ds);
                grd.DataSource = ds.Tables[0];
                grd.DataBind();
            }
        }
 
    }
    public DataTable LoadAll()
    {
        dynamic objDt;
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var objAdp = new SqlDataAdapter("usp_DeptRecords", objCon))
            {
                objAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
                var ds = new DataSet();
                objAdp.Fill(ds);
                objDt = ds.Tables[0];
            }
        }
        return objDt;
    }
    public void UpdateGrid(ref GridView grd, int index)
    {
 
        var row = grd.Rows[index];
        var ddlDept = (DropDownList)row.FindControl("dropDownDept");
        var txtFname = (TextBox)row.FindControl("txtFirstName");
        var txtLname = (TextBox)row.FindControl("txtLastName");
        var isActive = (RadioButtonList)row.FindControl("radioActive");
        var chkAct = (CheckBox)row.FindControl("chkActive");
 
        var id = Convert.ToInt32(grd.DataKeys[row.RowIndex].Value);
        var FNAME = txtFname.Text.ToUpper();
        var lname = txtLname.Text.ToUpper();
        var deptID = Convert.ToInt32(ddlDept.SelectedItem.Value);
        var isactive = isActive.SelectedValue == "True" ? Convert.ToInt32(1) : Convert.ToInt32(0);
        using (var objCon = new SqlConnection())
        {
            objCon.ConnectionString = ConfigurationManager.ConnectionStrings["cnGrid"].ConnectionString;
            if (objCon.State == ConnectionState.Closed)
                objCon.Open();
            using (var cmd = new SqlCommand("usp_PersonUpdate", objCon))
            {
                cmd.CommandType = CommandType.StoredProcedure;
 
                var parm = new[]
                               {
                                   new SqlParameter("@PersonID", SqlDbType.Int, Int32.MaxValue) {Value =id},
                                   new SqlParameter("@FName", SqlDbType.VarChar, 100) {Value =FNAME },
                                   new SqlParameter("@LName", SqlDbType.VarChar, 100) {Value = lname},
                                   new SqlParameter("@DeptID", SqlDbType.Int, Int32.MaxValue) {Value =deptID},
                                   new SqlParameter("@IsActive", SqlDbType.Bit) {  Value = isactive}
                               };
                cmd.Parameters.AddRange(parm);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                LoadPerson(ref grd);
            }
        }
    }
}

Now  Run by pressing F5 remember that before run to this ensure your database and connection string  in web config file and change in that setting of your MSSQLServer

<connectionStrings>
		<add name="cnGrid" connectionString="Data Source=xxxx;Initial Catalog=dbGrid;Persist Security Info=True;User ID=xxx;Password=xxx;Pooling=False" providerName="System.Data.SqlClient"/>
</connectionStrings>

Download Url : https://docs.google.com/file/d/0B-sDsBkcsM1YODBWaVZmLTJ6YlE/edit?usp=sharing

How To Get CheckBox Selected Values in Controller In MVC3


Introduction

In this article i am going to define u you how we can get selected values of checkbox in mvc3 in controller.in this article u will also get to know about multiple form in a single view how to use them.

Step 1: Make a new Empty Project using mvc3 in visual studio 2010.

Step 2: Now Add Collection Class in Model folder by Right click on model whose code would be such as below given.

 public class MyViewModel
    {
        public int Id { get; set; }
        public bool Checkbox { get; set; }
        public string Value { get; set; }
    }
 
 
    // view model for checklistbox
    public class CheckBoxListViewModel
    {
        public List<CheckListBoxItem> Items { get; set; }
 
        // the name of this list should be the same as of the CheckBoxes otherwise you will not get any result after post
        public List<string> SelectedValues { get; set; }
    }
 
    // represents single check box item
    public class CheckListBoxItem
    {
        public string Value { get; set; }
        public string Text { get; set; }
        public bool IsCheck { get; set; }
    }

Step 3: After this add a HomeController in Controller Folder and write in that below given code.

public ActionResult Index()
        { 
 
            var list = new List<MyViewModel>
            {
                new MyViewModel { Id = 1, Checkbox = false ,Value="Coal"},
                new MyViewModel { Id = 2, Checkbox= false ,Value="Cotton"},
                new MyViewModel { Id = 3, Checkbox = false ,Value = "Fabric"},
            };
            var outObj = list.Select(row => new SelectListItem()
                            {
                                Text = row.Value,
                                Value = row.Id.ToString(CultureInfo.InvariantCulture),
                                Selected = row.Checkbox
                            });
            ViewBag.keydata = outObj;
            // pass ViewModel object to View for display
 
            return View();
        }

Step 4 :  Now Add your view index.cshtml in view folder and paste in his below given code.

@{
    ViewBag.Title = "Index";
    var obj = ViewBag.keydata;
}
@using (Html.BeginForm("Index", "Home"))
{
    IEnumerable<SelectListItem> ct = ViewBag.keydata;
    foreach (var item in ct)
    {
    @Html.CheckBox("chk", item.Selected, new { value = item.Value });<label>@item.Text</label>
    }
<div>
       <input type="submit" value="Send" name="action:Send" /></div>
}

Step 5:  Now Make your Index Action with HttpPost Attribute in Controller which is below given.

 [HttpPost]
        [MultipleButton(Name = "action", Argument = "Send")]
        public ActionResult Index(FormCollection obj)
        {
           
            if (obj != null)
            {
                string[] AllStrings = obj["chk"].Split(',');
                foreach (string item in AllStrings)
                {
                    if (item.Contains("false"))
                    {
 
                    }
                    else
                    {
                        var outk = item;
                    }
 
 
 
                    // handle value
                }
            }
           
            return RedirectToAction("Index", "Home");
        }
Now Run by pressing f5 and See by putting Result in Your action you will get your all selected
Check boxes values.

If you Want to Download complete source of this article you can get to download it by click on below given url

https://docs.google.com/file/d/0B-sDsBkcsM1YWV9PWVUwYlVHRjA/edit?usp=sharing

Creating an expandable master-details table using DataTable Plugin of jQuery


Hello Friends today i need to display master details so i decided to do rnd on net after lot of effort i found a good jQuery datatable plugin that’s really awesome and intellgent.

if you want to creating fully functional tables with pagination, sorting, filtering features is an easy task if you use the jQuery DataTables plug-in. This plug-in enables you to add all of these functionalities to a plain HTML table using a single line of code as shown in the following example:

(‘#mygrid’).datatable();

but before this you will have to need some files such as jQuery Datatable and themes file.

Now i will explain u step by step my jQuery Datatable  plugin article.basically in this practical is composed in MVC3 +Razor view Engine and Entity Framework.

in my sample have Three views

1) Index –display to static static data

2) Server Side — display server side data of Action method using ajax request and also have Model help.

3) Ajax Loading — Display using complete ajax request data on view without model class help.

 

Step 1) First of all you will have to make a New Empty MVC3 Project using Visual Studio 2010 as below given in image :

Image

Step 2 : Now Make DataBase dbNestedDataTable and In that add Two Tables and Also add Some Dummy entries those tables.

for help you can use to below given sqlscript.

USE dbNestedDataTable

go

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Company]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[Company](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [Address] [varchar](100) NULL,
 CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Employee]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[Employee](
    [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [Position] [varchar](50) NULL,
    [Phone] [varchar](50) NULL,
    [Email] [varchar](50) NULL,
    [CompanyID] [int] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
    [EmployeeID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Employee_Company]’) AND parent_object_id = OBJECT_ID(N'[dbo].[Employee]’))
ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [FK_Employee_Company] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[Company] ([ID])
Step 3: Now Come back in ur web application and now add a controller by right click on controller folder with name of HomeController.

Image

Step 4 : Now go into home controller u will see a index action and by right click on View and Click on AddView u will get a new view in View->Home->index.cshtml as below given image.

 

 

 

 

 

Image

Step 5 : Now Click on Index.cshtml view and go into it’s source  and paste below given code.

@{
    ViewBag.Title = "Index";
}
 
    @section onReady
    {
    var oTable;
$('#companies tbody td img').click(function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('Math-minus-icon')) {
        /* This row is already open - close it */
        this.src = "/Content/Math-plus-icon.png";
        oTable.fnClose(nTr);
    }
    else {
        /* Open this row */
        this.src = "/Content/Math-minus-icon.png";
        var companyid = $(this).attr("rel");
        $.get("@Url.Action("CompanyEmployees","Home")?companyID=" + companyid, function (employees) {
            oTable.fnOpen(nTr, employees, 'details');
        });
    }
        });
        /* Initialize table and make first column non-sortable*/
oTable = $('#companies').dataTable({  "bJQueryUI": true,
                                        "aoColumns": [
                                        {   "bSortable": false,
                                            "bSearchable": false },
                                        null,
                                        null,
                                        null
                                ]
    });
}
 
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th>
                </th>
                <th>
                    Company name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Town
                </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <img src="/Content/Math-plus-icon.png" rel="1" style="cursor:pointer;" alt="expand/collapse">
                </td>
                <td>
                    Emkay Entertainments
                </td>
                <td>
                    Nobel House, Regent Centre
                </td>
                <td>
                    Lothian
                </td>
            </tr>
            <tr>
                <td>
                    <img src="/Content/Math-plus-icon.png" rel="2" style="cursor:pointer;" alt="expand/collapse">
                </td>
                <td>
                    The Empire
                </td>
                <td>
                    Milton Keynes Leisure Plaza
                </td>
                <td>
                    Buckinghamshire
                </td>
            </tr>
        </tbody>
    </table>
</div>

Step 6: Now You will have to go in _Layout.chstml page that's in Shared Folder in which you will
add some resources link and url which are below given.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/dataTables/demo_page.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table_jui.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" media="all" />
        <link href="@Url.Content("~/Content/themes/smoothness/jquery-ui-1.10.3.custom.min.css")"rel="stylesheet" type="text/css" media="all" />
        <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.dataTables.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            @RenderSection("onReady", required: false)
        });
    </script>
</head>
<body>
    <header class="ui-state-processing">
        <ul>
            <li>
        @Html.ActionLink("Static table", "Index", "Home")        
            </li>
        
        
            <li>@Html.ActionLink("Server-side generated table", "ServerSide", "Home")</li>
 
       <li> @Html.ActionLink("Ajax-loaded table", "Ajax", "Home")</li>
        </ul>
    </header>
    <div class="ui-widget-content">
        @RenderBody()
    </div>
</body>
</html>

Step 7 : Now Add new Entity model by right click on Model Folder and make connection with your database which u have been made in MSSQLSERVER and then
you will see that your application will give u below type image.
Image
Image
Step 8: Now add Two Methods in your home controller.
   public ActionResult CompanyEmployees(int? companyID)
        {
            var employees = GetEmployees();
            var companyEmployees = (from e in employees
                                    where (companyID == null || e.CompanyID == companyID)
                                    select e).ToList();
            return PartialView("CompanyEmployees", companyEmployees);
        }
        public IEnumerable<Employee> GetEmployees()
        {
            using (var db = new dbNestedDataTableEntities())
            {
                return db.Employees.ToList();
            }
        }
and complie then run by pressing F5 on Index page you will see that look as below given.
Image

Upto this you will get data static data display how using datatable plugin in
MVC3
now you will do Second Thing ServerSide Data How Bind to DataTable in MVC From View Action.
Add Two Method in Your homecontroller
  public ActionResult ServerSide()
        {
            var obj = GetCompanies();
            return View(obj);
        }
        public IEnumerable<Company> GetCompanies()
        {
            using (var db = new dbNestedDataTableEntities())
            {
                return db.Companies.ToList();
            }
        }
and Add a new view whose name is ServerSide.cshtml
in which source code will be such as.
@model IEnumerable< mvcwithnesteddatatable.Models.Company>
@{
    ViewBag.Title = "ServerSide";
}
@section onReady
    {
    var oTable;
$('#companies tbody td img').click(function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('Math-minus-icon')) {
        /* This row is already open - close it */
        this.src = "/Content/Math-plus-icon.png";
        oTable.fnClose(nTr);
    }
    else {
        /* Open this row */
        this.src = "/Content/Math-minus-icon.png";
        var companyid = $(this).attr("rel");
        $.get("@Url.Action("CompanyEmployees","Home")?companyID=" + companyid, function (employees) {
            oTable.fnOpen(nTr, employees, 'details');
        });
    }
        });
        /* Initialize table and make first column non-sortable*/
oTable = $('#companies').dataTable({  "bJQueryUI": true,
                                        "aoColumns": [
                                        {   "bSortable": false,
                                            "bSearchable": false },
                                        null,
                                        null,
                                        null
                                ]
    });
}
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th></th>
                <th>ID</th>
                <th>Company Name</th>
                <th>Town</th>
            </tr>
        </thead>
    @foreach (var item in Model) {
        <tr>
            <td><img src="/Content/Math-plus-icon.png" style="cursor:pointer;" alt="expand/collapse" rel="@item.ID"/></td>
            <td>@item.ID</td>
            <td>@item.Name</td>
            <td>@item.Address</td>
        </tr>
    }
    </table>
</div>
In Third phase of this article complete ajax request will do have to add a class in Model folder whose name is
JQueryDataTableParamModel.cs ,it's code will be such as
 /// <summary>
    /// Class that encapsulates most common parameters sent by DataTables plugin
    /// </summary>
    public class JQueryDataTableParamModel
    {
        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>       
        public string sEcho{ get; set; }
 
        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch{ get; set; }
 
        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength{ get; set; }
 
        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart{ get; set; }
 
        /// <summary>
        /// Number of columns in table
        /// </summary>
        public int iColumns{ get; set; }
 
        /// <summary>
        /// Number of columns that are used in sorting
        /// </summary>
        public int iSortingCols{ get; set; }
 
        /// <summary>
        /// Comma separated list of column names
        /// </summary>
        public string sColumns{ get; set; }
 
    }

After add this code in your class file go into homecontroller and add two more methods which are
below given.


public ActionResult Ajax()
        {
            return View();
        }
        /// <summary>
        /// Returns data by the criterion
        /// </summary>
        /// <param name="param">Request sent by DataTables plugin</param>
        /// <returns>JSON text used to display data
        /// <list type="">
        /// <item>sEcho - same value as in the input parameter</item>
        /// <item>iTotalRecords - Total number of unfiltered data. This value is used in the message: 
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>iTotalDisplayRecords - Total number of filtered data. This value is used in the message: 
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>aoData - Twodimensional array of values that will be displayed in table. 
        /// Number of columns must match the number of columns in table and number of rows is equal to the number of records that should be displayed in the table</item>
        /// </list>
        /// </returns>
        public ActionResult AjaxHandler(JQueryDataTableParamModel param)
        {
            var allCompanies = GetCompanies();
            IEnumerable<Company> filteredCompanies;
            //Check whether the companies should be filtered by keyword
            if (!string.IsNullOrEmpty(param.sSearch))
            {
                //Used if particulare columns are filtered 
                var nameFilter = Convert.ToString(Request["sSearch_1"]);
                var addressFilter = Convert.ToString(Request["sSearch_2"]);
                var townFilter = Convert.ToString(Request["sSearch_3"]);
 
                //Optionally check whether the columns are searchable at all 
                var isNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                var isAddressSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
                var isTownSearchable = Convert.ToBoolean(Request["bSearchable_3"]);
 
                filteredCompanies = GetCompanies()
                   .Where(c => isNameSearchable && c.Name.ToLower().Contains(param.sSearch.ToLower())
                               ||
                               isAddressSearchable && c.Address.ToLower().Contains(param.sSearch.ToLower())
                               );
            }
            else
            {
                filteredCompanies = allCompanies;
            }
 
            var isNameSortable = Convert.ToBoolean(Request["bSortable_1"]);
            var isAddressSortable = Convert.ToBoolean(Request["bSortable_2"]);
            var isTownSortable = Convert.ToBoolean(Request["bSortable_3"]);
            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<Company, string> orderingFunction = (c => sortColumnIndex == 1 && isNameSortable ? c.Name :
                                                           sortColumnIndex == 2 && isAddressSortable ? c.Address :
                                                           "");
 
            var sortDirection = Request["sSortDir_0"]; // asc or desc
            if (sortDirection == "asc")
                filteredCompanies = filteredCompanies.OrderBy(orderingFunction);
            else
                filteredCompanies = filteredCompanies.OrderByDescending(orderingFunction);
 
            var displayedCompanies = filteredCompanies.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var result = from c in displayedCompanies select new[] { Convert.ToString(c.ID), c.Name, c.Address };
            return Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = allCompanies.Count(),
                iTotalDisplayRecords = filteredCompanies.Count(),
                aaData = result
            },
                        JsonRequestBehavior.AllowGet);
        }
        
      
    }
After adding these two methods make a new view with Ajax.cshtml name and in that source code will be
@{
    ViewBag.Title = "Ajax";
}
@section onReady
{
 
    var oTable;
    $('#companies tbody td img').live('click', function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('details_close')) {
    /* This row is already open - close it */
    this.src = "@Url.Content("/Content/images/details_open.png")";
    oTable.fnClose(nTr);
    }
    else {
    @*/* Open this row */*@
    this.src = "@Url.Content("/Content/images/details_close.png")";
    var companyid = $(this).attr("rel");
    $.get("@Url.Action("CompanyEmployees", "Home")?companyID=" + companyid, function (employees) {
    oTable.fnOpen(nTr, employees, 'details');
    });
    }
    });
 
    
    @*/* Initialize table and make first column non-sortable*/*@
    
    
      oTable = $('#companies').dataTable({
                                    "bProcessing": true,
                                    "bServerSide": true,
                                    "sAjaxSource": 'AjaxHandler',
                                    "bJQueryUI": true,
                                    "aoColumns": [
			                                    { "bSortable": false, "bSearchable": false,
			                                        "fnRender": function (oObj) {
			                                            return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + oObj.aData[0] + '"/>';
			                                        } 
			                                    },
			                                  { "sName": "Name" },
    { "sName": "Address" }
    ],
    
        });
 
}
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th>ID</th>
                <th>Company Name</th>
                <th>Town</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>



Now Run Your Application and See Result on Click of three links and observer the difference also enjoy
your programming.
If you want to download this practical source complete get to it by below given url.
https://docs.google.com/file/d/0B-sDsBkcsM1Yc0ZRQlM5S1Z4MFE/edit?usp=sharing