Using a Webgrid that can sort, page, and filter in Asp.Net MVC3


Getting the MvcWebGrid app setup

To begin, create a new MVC3 application called MvcWebGrid.  Make sure you select Empty for the template, and that the view engine is set to Razor.  Next, right click on the Controllers folder and select add->New Controller.  Name the controller HomeControler, and leave the checkbox to create the CRUD methods unchecked.

For simplicity sake, we will not connect to a real database in this sample.  Instead, I have created a class that returns a lists of music albums (generated from the MvcMusicStore tutorial at mvcmusicstore.codeplex.com).  You can find this class in the code download (linked at the end of this article), or here on github.  This is a simple static class with a single method called GetAlbums, which returns an IEnumerable<Album>.  Add this class to your models folder.

In your home controller, modify your Index action method to like like so:

  public ActionResult Index()
        {
            var obj = new AlbumRepo();
            var albums = obj.GetAlbums();
            return View(albums);
        }

In _LayouPage write down below given code
 <div id="header">
        Welcome to my awesome music site where a deep dish of awesome stew is served up
        daily
        <p />
        <p />
        <p />
        <ul>
            <li>@Html.ActionLink("Index", "Index", "Grid")</li>
            <li>@Html.ActionLink("Ajax2", "IndexWithAjax","Grid",new { ajax = "this is ajax sample" },null)</li>
        </ul>
    </div>
    @RenderBody()
    <div id="footer">
        <p />
        You have reached the bottom of this page, now what?
    </div>

Adding the WebGrid to the app

Now that we have a basic layout for our site, lets create the index view.  Go back to the home controller, right click anywhere within the index action method, and select add view.  Keep all the defaults and click Add.

Change the new view to look like the following:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      ViewBag.Title = "MVC Music Store Grid";
   5:  }
   6:   
   7:  @using (Html.BeginForm())
   8:  {
   9:      <fieldset>
  10:          <legend>Search</legend>
  11:   
  12:          <div>
  13:              Album Id:
  14:          </div>
  15:          <div>
  16:              <input type="text" id="albumid" name="albumid" />
  17:          </div>
  18:   
  19:          <div>
  20:              Album Name:
  21:          </div>
  22:          <div>
  23:              <input type="text" id="albumName" name="albumName" />
  24:          </div>
  25:   
  26:          <p>
  27:              <input type="submit" value="Search" />
  28:          </p>
  29:      </fieldset>
  30:  }
  31:   
  32:  <div id="myGrid">
  33:      @Html.Partial("_grid", Model)
  34:  </div>

We will be separating the WebGrid into its own partial view, so right click on the Views/Home folder, select add, and then view.  Name the view _grid, and check the “Create as a partial view” checkbox, then click add.  Prepending the name of our Razor view with a underscore tells Asp.Net that this file should not be served if requested directly, which is perfect for our partial views.

In our grid partial view, we will now be using the new WebGrid helper.  We start off creating an instance of the WebGrid (passing in our model into the constructor), and then call the GetHtml method which generates the html for the grid and outputs it to the screen:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      var grid = new WebGrid(Model);
   5:      @grid.GetHtml();
   6:  }

When we run the app, we get a web page that looks like so:

image

If you inspect the html for the new grid, you will see that it is clean markup, with no added styles or nasty viewstate that we have seen in the past with WebForms.  You might also notice that the table html is semantically correct, where the header is in the thead section, the content in the tbody section, and the paging in the tfoot section.  Having your tables formatted properly will go a long ways if you want to try to extend your table functionality using JavaScript libraries such as jQuery, where it was often difficult to achieve this in WebForms.

Another bonus is that the paging and sorting already work!  Out of the box, the WebGrid provides these functions by doing Get requests and passing in a few values over the query string.  The WebGrid will see these values in the new request, and adjust the output accordingly.  This means that the WebGrid expects the entire set of data in each view in order to generate the paging properly.  For small sets of data this is not a problem, but even in our sample app you can notice a lag when hitting the links.  Fixing this issue is out of the scope of this article, but just be aware that you will need to come up with a different solution if your data sets are large.

The WebGrid provides a lot of options for configuration.  These options are provided by passing in parameters to the WebGrid’s constructor, as well as the GetHtml method.

image

image

We will modify some of these options to add some Ajax functionality to the screen (so that paging and sorting don’t refresh the entire screen), as well as change how some of the columns appear.  Modify _grid.cshtml to look like so:

   1:  @model IEnumerable<Album>
   2:   
   3:  @{
   4:      var grid = new WebGrid(Model, rowsPerPage: 15, ajaxUpdateContainerId: "myGrid");
   5:      @grid.GetHtml(columns: grid.Columns(
   6:                          grid.Column("AlbumId", "Album Id"),
   7:                          grid.Column("Title", "Title"),
   8:                          grid.Column("Artist", "Artist")
   9:                          ));
  10:  }

In the constructor, we setting the size of the page to handle 15 albums at a time, as well as setting the container id of the div in the index.cshtml page that holds our grid.  The simple act of setting the ajaxUpdateContainerId will automatically enable our screen to use Ajax to update the screen on pages and sorts.  All we need to do is make sure jQuery is included in the project, which it is by default in the _Layout.cshtml page.

The GetHtml method take a columns param, where we pass in a list of column objects we want to use on the grid.

One thing I don’t particularly care for is how the Ajax is inserted into the page.  If you take a look at the source, all of the links now have onclick methods inserted into them.  This gets away from the unobtrusive JavaScript theme the rest of MVC3 strived so hard to achieve.  We will talk some more about unobtrusive JavaScript in the next section.

Filtering the grid

You probably noticed that our index.cshtml page has had a form in it that we will be using to filter the data in the grid.  This form is simple by design, and will allow us to filter the form either by the Album Id, or the Album Name.  Before we do anything with the form, lets add a new action method in our home controller that will let us filter the data:

   1:  [HttpPost]
   2:  public ActionResult Index(int? albumId, string albumName)
   3:  {
   4:      var albums = AlbumRepo.GetAlbums();
   5:   
   6:      if (!string.IsNullOrEmpty(albumName))
   7:          albums = albums.Where(a => a.Title.Contains(albumName)).ToList();
   8:   
   9:      if (albumId.HasValue)
  10:          albums = albums.Where(a => a.AlbumId == albumId).ToList();
  11:   
  12:      return View(albums);
  13:  }
 
This new action method has the same name as our other action method, but has the HttpPost attribute which tells MVC that this method will only respond to post requests.  We accept two params into the method that will be used to filter the data. (Note: the code in this action method is not a good way to filter data, it is just demo code, so don’t reuse it in production).
Now when we run the app, we can filter the data.  However, our site is doing a complete post and refresh of the page every time we do a search.  We will now add Ajax to the form.
We will use the new unobtrusive Ajax support that is in MVC3 to accomplish this, and do it without having to write a single line of JavaScript.  The Ajax.BeginForm has been around for awhile in MVC, but it has been changed to now use jQuery and not the Microsoft Ajax library.  Also, there is no more JavaScript inserted into the screen on your behalf (unlike the WebGrid Ajax support shown above).  Instead, MVC3 uses HTML5 data attributes to mark the form, and a special script that is used to wire the Ajax functionality up at runtime.
In index.cshtml, change the Html.BeginForm line to the following:
   1:  @using (Ajax.BeginForm(new AjaxOptions 
   2:      { InsertionMode = InsertionMode.Replace, UpdateTargetId = "myGrid" }))
   3:  {
The AjaxOptions parameter tells our form how to handle the Ajax reqeuest.  In this case, we are telling it we want the InsertionMode to replace the current contents in the myGrid div tag (much like we did with the paging and sorting on the grid).  All that is left to do is add the JavaScript file that will make this magic happen.  In the _Layout.cshtml file, add the following line directly below the line that includes jQuery:
   1:  <script type="text/javascript" src="../../Scripts/jquery.unobtrusive-ajax.min.js">
   2:  </script>  

Make sure you don’t include any of the JavaScript files that start with Microsoft, as those are just included for backwards compatibility.  In MVC3, you want to be using the scripts who’s filenames start with jQuery.

If you run the app now, you might notice a strange oddity when filtering the data.  The entire response is copied into the myDiv tag, meaning that we get another copy of the form, along with the WebGrid table again.  When using Ajax.BeginForm, the response that is sent is expected to only be the content that changes, not the entire page.  We can easily fix this and return just the updated grid by changing the index action method that accepts the HttpPost to return a partial view of only the grid and not the entire index view (this is why we separated the grid out from the index view in the first place).

Update the index action method for the filtering to return a partial view by modifying the last line as such:

   1:  return PartialView("_grid", albums);

Now when you enter an a AlbumId or a partial Album name, the grid will filter and display properly.

Download Source Code : https://docs.google.com/file/d/0B-sDsBkcsM1YVUJwSUN0YWJFTU0/edit?usp=sharing

Advertisements

Differences between viewdata, viewbag and tempdata in mvc3


Differences between viewdata, viewbag and tempdata in mvc3

 

In Asp.net MVC, we have three objects – ViewData, ViewBag and TempData to pass data from controller to view and in next request.

ViewData

1.ViewData is a dictionary object that is derived from ViewDataDictionary class.

2.ViewData is used to pass data from controller to corresponding view.

3.It’s life lies only during the current request.

4.If redirection occurs then it’s value becomes null.

5.It’s required typecasting for complex data type and check for null values to avoid error.

ViewBag

1.ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

2.Basically it is a wrapper around the ViewData and also used to pass data from controller to      corresponding view.

3.It’s life also lies only during the current request.

4.If redirection occurs then it’s value becomes null.

5.It doesn’t required typecasting for complex data type.

TempData

1.TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.

2.TempData is used to pass data from current request to subsequent request means incase of redirection.

3.It’s life is very short and lies only till the target view is fully loaded.

4.It’s required typecasting for complex data type and check for null values to avoid error.

5.It is used to store only one time messages like error messages, validation messages.

ViewData, ViewBag and TempData Current Request Example

public class HomeController : Controller
{
public ActionResult Index()
{
var cust= new Customer
{
CustID=101,
Name = "Rajesh",

};
ViewData["cust"] = cust;
ViewBag.Customer = cust;
TempData["cust"] = cust;
return View();
}
}

return View(); }
}
@model MvcSample.Models.CustomerModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Welcome to MVC Tutorails";
var viewDataCustomer = ViewData["cust"] as Customer; //need typcasting
var tempDataCustomer = TempData["cust"] as Customer; //need typcasting
}
<h2>Welcome to MVC Tutorials</h2>
This Best behavioral customer is!
<h4>@ViewBag.cust.Name</h4>
<h3>@viewDataCustomer.Name</h3>
<h2>@tempDataCustomer.Name</h2>
</div>

ViewData, ViewBag and TempData Next Request Example

public ActionResult About()
{
var cust= new Customer {
CustID=007,
Name = "Rajesh",
};
ViewData["cust"] = cust;
ViewBag.Customer = cust;
TempData["cust"] = cust;
//After the redirection, ViewData and ViewBag objects will be null
//Only TempData will exist after redirection
return View();
}
@model MvcSample.Models.Customermodel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Detail";
var tempDataCustomer = TempData["cust"] as Customer; //need typcasting
}

CheckBoxList in ASP.Net MVC3 Razor


CheckBoxList in ASP.Net MVC3 Razor

 

If we want to create many check boxes or check boxes list we can call it inside a loop as follows.

1
2
3
4
@foreach (var item in MyCollection)
{
@Html.CheckBox("checkBoxName", new {value=item.checkBoxValue })@item.CheckBoxText<br />
}

 

Here is a generic extension method for create a check boxes list in an elegant manner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static MvcHtmlString CheckBoxList<T>(this HtmlHelper helper,
String name,
IEnumerable<T> items,
String textField,
String valueField,
IEnumerable<T> selectedItems=null)
{
Type itemstype = typeof(T);
PropertyInfo textfieldInfo = itemstype.GetProperty(textField,typeof(String));
PropertyInfo valuefieldInfo = itemstype.GetProperty(valueField);
 
TagBuilder tag;
StringBuilder checklist = new StringBuilder();
foreach(var item in items)
{
tag = new TagBuilder("input");
tag.Attributes["type"] = "checkbox";
tag.Attributes["value"] = valuefieldInfo.GetValue(item,null).ToString();
tag.Attributes["name"] = name;
if (selectedItems != null && selectedItems.Contains(item))
{
tag.Attributes["checked"] = "checked";
}
tag.InnerHtml = textfieldInfo.GetValue(item,null).ToString();
checklist.Append(tag.ToString());
checklist.Append("<br />");
}
return MvcHtmlString.Create(checklist.ToString());
}

In the first three lines we get the type of the data collection then get the property info of text field and value field that will be used to create each check box. We enumerate over the input data collection and use  TagBuilder class to create input tag and set its attributes like type,name, and value. We check the selectedItems collection to set checked attribute of our check box.

Say we have a list of users that we display it as checkboxlist to select some users, we can use our helper method as follows

1
@Html.CheckBoxList("SelectedUsers", AllUsersList, "Name", "ID")

To get the values of checked users we have two scenarios:
Strongly typed model scenario:
The model must have pro

perty with the same name that we provided to our helper method.

1
2
3
4
5
6
class MyModel
{
//Note you can define it as array of strings, dates or any primitive data type
//according to the type of the property of value field.
Public Int32[] SelectedUsers{get; set;}
}

when we post the view, the model binder will bind the values of selected check boxes into the property with the same name.

Not Strongly typed model scenario:
In this case, our action method that will handle our request(decorated by HttpPost attribute) should be defined to accept a FormCollection parameter that will contain key with the same name we provided to our helper method

1
2
3
4
5
6
[HttpPost]
public ActionResult ActionMethodName(FormCollection myForm)
{
String selectedusers = myForm["SelectedUsers"];
//Note this will return the selected users ids as comma separated string.
}

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

WORKING OF CONTROLLER IN MVC


The ASP.NET MVC framework maps URLs to classes that are referred to as controllers. Controllers process incoming requests, handle user input and interactions, and execute appropriate application logic. A controller class typically calls a separate view component to generate the HTML markup for the request.

The base class for all controllers is the ControllerBase class, which provides general MVC handling. The Controller class inherits from ControllerBase and is the default implement of a controller. The Controller class is responsible for the following processing stages:

  • Locating the appropriate action method to call and validating that it can be called.
  • Getting the values to use as the action method’s arguments.
  • Handling all errors that might occur during the execution of the action method.
  • Providing the default WebFormViewEngine class for rendering ASP.NET page types (views).

What is MVC (a Single Line Definition)?


Model–view–controller, an architectural pattern used in software developmentModel–view–conModel–view–controller, an architectural pattern used in software developmentModel–view–controller, an architectural pattern used in software developmenttroller, an architectural pattern used in software development

The primary thing you need to know about MVC is how logic can be distributed:

Model
Business logic goes here
View
Presentation logic goes here
Controller
Application logic goes here
MVC WORKING FLOW

MVC