How To Reload And Update Mvc View Automatically When Inputs Change
This article shows how to easily reload table content in ASP.NET MVC using the jQuery DataTables plug-in. Minimal code is required on the customer-side, and on the server-side, nosotros demand standard processing functions. This plug-in allows you to create an effective, AJAXified, Web 2.0 interface with minimal effort and straightforward implementation guidelines.
- Download source code - 247 KB
Table of Contents
- Introduction
- Background
- Using the Code
- Model
- View
- Controller
- Summary
- History
Introduction
In this article, I will show how y'all can refresh an HTML table content via AJAX. If you lot are using regular HTML tables, reloading the table is not a very complicated task. All you lot demand to practice is send an AJAX request to the server-side page, take the response from the server, and put it in the tabular array. I believe that this is something that you accept washed a lot of times. There is a simple jQuery code that can exercise this:
$(" table#employees tbody").load(" TableContent.aspx");
This call will send an AJAX call to the server-side page TableContent.aspx, read the response that TableContent.aspx provides, and put information technology into the body of the table. In the TableContent.aspx page, you volition demand to return a valid HTML representing the ready of rows that will be placed in the table.
This works fine if yous have a uncomplicated table where you can replace content with response from the server. Withal, if yous have some advanced functionalities such as pagination, sorting, filtering, this might become more complicated. When you lot send a request to the server, yous will need to include data about the current page and table state, and make certain that you have loaded proper content, selected the correct folio number in the pagination, etc. If y'all take more advanced tables, information technology would be better to use some existing component where the refresh functionality is already built-in.
My option is the jQuery DataTables plug-in. With the jQuery DataTables plug-in, yous can take a plain table and add together pagination, filtering, and sorting using a single JavaScript line of lawmaking:
var oEmployeesTable = $(' table#employees').dataTable();
In this example is taken a apparently HTML table with id "employees
" and the DataTables plug-in is practical to the table. This call will add pagination, sorting, and filtering on the table.
You can besides easily create a fully AJAXified table using a slightly different call:
var oEmployeesTable = $(' table#employees').dataTable({ " bServerSide": true, " sAjaxSource": " DataContent.aspx" });
In this instance are set two parameters specifying that information volition exist taken not from the HTML but from the server-side page DataContent.aspx.
If you lot use DataTables to refresh the table content, you will need to execute a single line of JavaScript code:
oEmployeesTable.fnDraw();
This telephone call will refresh the table content. In this article, I will prove how yous can implement refresh functionality in the ASP.Cyberspace MVC application.
Background
The jQuery DataTables plug-in is an excellent jQuery library that enables you to create fully AJAXified tables with minimal attempt. To create an AJAXified table with the jQuery DataTables plug-in, y'all will demand to implement the following elements:
- Put an empty table in the HTML of the folio. This empty table volition define the construction of the table (due east.g., columns, styles, etc.). The table should accept only a heading in the
THEAD
element, empty body, and an optional footer in theTFOOT
element. Rows in the tabular array are not required because they will be loaded via an AJAX call. - Create some server-side page that will provide rows to the tabular array when it is called via AJAX. In this commodity, an ASP.Net MVC controller that will provide data rows to the table volition be implemented.
- Initiate the jQuery DataTables plug-in to load tabular array content from the controller.
Equally a consequence, instead of an empty table, you will get a fully AJAXified table where jQuery DataTables has automatically added pagination, sorting by table headings, and filtering by keyword. An example of the table is shown in the post-obit figure:
As you tin can see, the jQuery DataTables plugin has taken a obviously table with no content, populated it with rows via an AJAX telephone call, and added elements for sorting, filtering, and pagination. You volition see in the following sections that the merely thing that is needed are a few lines of JavaScript lawmaking to initialize this table, and convert information technology to the fully functional AJAXified tabular array.
Yous tin can observe detailed instructions about the integration of the jQuery DataTables plug-in with the ASP.NET MVC controller in the jQuery DataTables and ASP.Internet MVC Integration - Office I article.
Once yous implement the controller and initialize the jQuery DataTables plug-in, it will handle the complete interaction with the user. Each time the user changes the state of the tabular array (eastward.g., alter page using pagination, sort rows by column, or perform some search) the DataTables plug-in will ship information to the controller and refresh the content of the table.
However, in some cases, you will demand to refresh the table content manually. Refreshing the table content is a mutual requirement in many applications - some examples are:
- You might want to add a Refresh button that enables the user to refresh the data displayed in the table.
- You might desire to implement some journal refresh of table content to provide the latest data to the user (e.g., some live scores implementation).
- You lot might want to implement some kind of AJAXified search where the user enters search benchmark in the grade and you want to refresh data in the tabular array without refreshing the whole page.
- Yous might want to add some principal tabular array or drop-down so when the user selects some value in the tabular array or dropdown, you might want to refresh the dependent table.
- You might want to add some filter to the table where the user volition blazon some text or select some value in the dropdown list, so yous will need to refresh the table content to friction match the filter.
To implement these scenarios, y'all will need to refresh the DataTables content. The goal of this article is to show how you can practice it with the API provided by the jQuery DataTables plug-in.
This is the third article in the series explaining how the jQuery DataTables plug-in can be integrated in an ASP.NET MVC web application. If yous are not familiar with the integration of the DataTables plug-in with the ASP.NET MVC server-side code, you might want to read the offset article in this series before you continue.
Using the Code
For illustrative purposes, we'll utilise a uncomplicated ASP.Net MVC spider web application to list the employees. The first thing yous need to do is to create a standard ASP.NET Model-View-Controller structure. There are three steps required for this setup:
- Creating the model classes that correspond a data structure to be shown.
- Creating the controller class that volition react on the user events.
- Creating the view that will render the information and create the HTML code that is sent to the browser window.
Besides, you will demand to include some JavaScript components in your projection. The following JavaScript components need to be downloaded:
- jQuery library v1.4.4., containing the standard classes used by the DataTables plug-in.
- jQuery DataTables plug-in v1.7.5., including the optional DataTables CSS style-sheets used for applying the default styles on the folio.
These files should exist stored in the local file system and included in the HTML folio that is rendered on the client. An example of usage of these files is explained beneath.
Model
Ii classes that contain information nigh companies and employees need to be added in the case. The classes are shown in the following listing:
public class Company { public int ID { get; set; } public string Name { get; set; } public string Accost { get; fix; } public cord Boondocks { become; gear up; } } public grade Employee { public int EmployeeID { become; set; } public string Proper noun { get; set; } public string Position { get; prepare; } public int CompanyID { become; set; } }
The employees are connected to the companies via the CompanyID
property. These classes volition be used to show information on the page.
View
The view is used to render data on the server-side and to send HTML code to the browser. There'southward 1 layout folio that is used to include all the necessary CSS and JavaScript files that are used on the page. This layout page is shown below:
< !DOCTYPE html > < html > < head > < title >Refreshing table content using a JQuery DataTables plugin< /title > < link href =" @Url.Content(" ~/Content/dataTables/demo_page.css " ) " rel =" stylesheet" blazon =" 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" blazon =" 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-one.seven.2.custom.css " ) " rel =" stylesheet" type =" text/css" media =" all" / > < script src =" @Url.Content(" ~/Scripts/jquery-1.iv.4.min.js " ) " blazon =" text/javascript" > < / script > < script src =" @Url.Content(" ~/Scripts/jquery.dataTables.min.js " ) " type =" text/javascript" > < / script > @RenderSection("head", required: false) < /head > < body id =" dt_example" > < div id =" container" > @RenderBody() < /div > < /body > < /html >
The layout folio has 2 sections that can be populated on the page:
-
head
section where the JavaScript calls from the folio will be injected -
body
section that enables the folio that uses this layout page to inject lawmaking to the page that volition exist shown on the page
In the following sections, I will show a few implementations of the pages that use this layout page and refresh the table content.
Case one - Adding the "Refresh" Button
In the starting time example, I volition show how you can add a Refresh button that volition reload the content of the table when the user presses it. An case is shown in the following figure:
Equally described above, we would need an empty table that holds table data and a refresh push button. The body of the folio is shown in the following listing:
< button id =" Refresh" blazon =" push" >Refresh< button/ > < table id =" employees" class =" brandish" > < thead > < tr > < thursday >ID< /th > < th >Employee< /th > < th >Position< /th > < /tr > < /thead > < tbody > < /tbody > < /table >
Once we have prepared static HTML, we would need to initialize the DataTables plug-in, and attach a click handler to the refresh button that will redraw the table. Instance of code is shown in the following listing.
@department head{ <script language=" javascript" blazon=" text/javascript"> $(document).ready(role () { var oEmployeesTable = $(' #employees').dataTable({ " bJQueryUI": true, " bServerSide": truthful, " sAjaxSource": " MasterDetailsAjaxHandler" }); $(" #Refresh").click(office (e) { oEmployeesTable.fnDraw(); }); }); </script> }
This code should be placed in the head
section of the view. The first argument in the document ready function applies the DataTables
plug-in on the employees
table, specified that information technology will work in server-side mode (significant that on each user activity, the plug-in will ask the server-side folio to provide new data that should be displayed), defines that URL that will exist chosen via an AJAX phone call is MasterDetailsAjaxHandler
- this is the path of the controller that volition provide the content of the tabular array. The bJQueryUI
flag is not mandatory - it is simply used to use jQuery UI styles to the table.
When the table is initialized, in the code is added a click handler for the refresh button that volition draw the content of the tabular array. On each describe telephone call, the DataTables
plug-in will call the server-side page over again and accept the new set of information which will exist loaded in the table torso.
The controller that provides content is described in the section controller.
Case two - Refreshing Table Content Periodically
If you practice not desire to strength the user to refresh the table, yous can add a function that will exist periodically called to refresh the tabular array. The code is very similar to the code shown in case i. The only difference is that the refresh push is not needed and instead of the click handler is used a gear up interval function equally shown in the post-obit listing:
@section head{ <script language=" javascript" type=" text/javascript"> var oEmployeesTable = null; office refresh() { if (oEmployeesTable != naught) oEmployeesTable.fnDraw(); } setInterval(" refresh()", 1000); $(document).gear up(office () { oEmployeesTable = $(' #employees').dataTable({ " bJQueryUI": true, " bServerSide": truthful, " sAjaxSource": " /Abode/MasterDetailsAjaxHandler" }); }); </script> }
In the global scope are defined references to the employees
table, function that refreshes the table, and a timer that calls the refresh function each second. Then, in the document ready handler, the employees
tabular array is initialized with the DataTables
plug-in and a global reference is set.
As a result, this table volition exist automatically reloaded each second. A trace of the AJAX calls that are sent to the server is shown on the effigy below:
Note that the reference to the employees
table, function and interval phone call are placed in the global scope and not in the body of the document ready handler, because these function references will exist lost once the document ready handler finishes.
Case 3 - Refreshing Table Content when Parent Row is Selected
In this instance, I will show how you can refresh the content of the dependent table (employees
) when a company is selected in the main tabular array. In this instance, we will accept 2 tables - a parent table containing the list of companies and a child table containing the list of employees. An example of that kind of page is shown in the following figure:
When the user selects the company in the master table, in the child table will be shown the employees that vest to this company. The body of the folio is shown in the following listing:
< div id =" demo" > < table id =" companies" form =" brandish" > < thead > < tr > < th >Company name< /thursday > < th >Address< /thursday > < th >Town< /th > < /tr > < /thead > < tbody > < tr id =" 0" course =" masterlink" > < td >Emkay Entertainments< /td > < td >Nobel House, Regent Heart< /td > < td >Lothian< /td > < /tr > < tr id =" 1" class =" masterlink" > < td >The Empire< /td > < td >Milton Keynes Leisure Plaza< /td > < td >Buckinghamshire< /td > < /tr > < tr id =" two" course =" masterlink" > < td >Asadul Ltd< /td > < td >Hophouse< /td > < td >Essex< /td > < /tr > < tr id =" three" class =" masterlink" > < td >Ashley Mark Publishing Visitor< /td > < td >1-2 Vance Court< /td > < td >Tyne & Wear< /td > < /tr > < tr id =" 4" grade =" masterlink" > < td >MuchMoreMusic Studios< /td > < td >Unit of measurement 29< /td > < td >London< /td > < /tr > < tr id =" v" form =" masterlink" > < td >Sound Records Studios< /td > < td >Oxford Street< /td > < td >London< /td > < /tr > < /tbody > < /table > < tabular array id =" employees" class =" display" > < thead > < tr > < th >ID< /th > < th >Employee< /th > < th >Position< /th > < /tr > < /thead > < tbody > < /tbody > < /table > < /div >
The first table with companies contains a list of five companies, and the employees
tabular array is empty. The employees
table volition be populated with AJAX JavaScript calls. Each row in the companies
table contains the ID of the company - this information volition be used to load the employees
for the selected visitor.
The caput
section holds the JavaScript code that initializes and connects these 2 tables. The JavaScript initialization code is shown in the post-obit list:
<script linguistic communication=" javascript" type=" text/javascript"> $(document).prepare(role () { var oCompaniesTable = $(' #companies').dataTable({ " bJQueryUI": true }); $(" #companies tbody").click(function (outcome) { $(oCompaniesTable.fnSettings().aoData).each(office () { $(this.nTr).removeClass(' row_selected'); }); $(effect.target.parentNode).addClass(' row_selected'); }); var MasterRecordID = zippo; var oEmployeesTable = $(' #employees').dataTable({ " sScrollY": " 100px", " bJQueryUI": true, " bServerSide": true, " sAjaxSource": " MasterDetailsAjaxHandler", " bProcessing": true, " fnServerData": role (sSource, aoData, fnCallback) { aoData.button({ " name": " CompanyID", " value": MasterRecordID }); $.getJSON(sSource, aoData, function (json) { fnCallback(json) }); } }); $(" .masterlink").click(function (eastward) { MasterRecordID = $(this).attr(" id"); oEmployeesTable.fnDraw(); }); }); </script>
The first 2 statements are optional. The start statement initializes the companies table with the jQuery DataTables plug-in in order to add pagination, filtering, and sorting functionality (this is not required for the parent-child relationship between the tables because the parent table can be a plain tabular array). The 2d statement adds the row_selected
class on the selected row in the parent tabular array. This is besides not required, but it'due south useful to highlight a visitor whose employees
are shown in the child table.
A local variable MasterRecordID
is used to hold the ID of the currently selected visitor. The quaternary statement initializes the kid employees
table. Most of the settings are optional and do not impact the parent-child configuration because the simply relevant statements in the initialization are:
- Server-side processing configuration implemented using the
bServerSide
andsAjaxSource
parameters, -
fnServerData
method used to inject the ID of the selected company into the AJAX call sent to the server-side. This method is used to add the additional parameter calledCompanyID
with the value of theMasterRecordID
variable to the AJAX telephone call sent to the server-side.
The last argument attaches the event handler which populates the ID of the selected row and forces the redraw of the child table on each click on a row in the parent table. Redrawing of the table sends an AJAX request to the server-side and updates the table with the employee
records that belong to the selected company
.
Case four - Refreshing Table when Form is Posted
A common scenario when you might need to reload a tabular array is you post some form content via AJAX and yous want to reload the table to refresh the rows. As an example, you might add some add form in the page, and when a new particular is successfully added, you might want to reload the table content. An example of that kind of form is shown in the post-obit figure.
In order to create that kind of functionality, we would need to add together a button and a dialog to the view. The view body looks like the following HTML lawmaking:
< div id =" dialog" title =" Add new item" > < label for =" proper noun" >Title< /label > < input type =" text" id =" name" proper noun =" proper noun" value =" " / > < button blazon =" push button" id =" relieve" >Save< /push > < /div > < button id =" add" >Add< /push button > < table id =" employees" form =" display" > < thead > < tr > < th >ID< /th > < th >Employee< /th > < thursday >Position< /thursday > < /tr > < /thead > < tbody > < /tbody > < /table >
A dialog is added in HTML where are placed text input for the new detail and a Save button. Also, a push button that is used to open a dialog is added above the table. The table that is enhanced with the DataTables
plug-in is the same equally in the previous cases.
Now we would need to refresh the table subsequently the Save button posts request to the server-side. In this example, we would need to telephone call the role fnDraw
in the success handler of the AJAX call. An example of that kind of JavaScript code is shown in the post-obit listing:
var oEmployeesTable = $(' #employees').dataTable({ " bJQueryUI": true, " bServerSide": true, " sAjaxSource": " /Dwelling house/MasterDetailsAjaxHandler" }); $(" #dialog").dialog({ autoOpen: false }); $(" #add").click(function (e) { $(" #dialog").dialog(" open"); }); $(" #save").click(role (e) { e.preventDefault(); e.stopPropagation(); $.ajax({ url: " /Home/AddItem", data: { proper noun: function(){$(" #name").val();} }, success: function () { $(" #dialog").dialog(" close"); oEmployeesTable.fnDraw(); } }); });
The start part is a standard initialization of DataTable
as in the previous examples. Then the dialog is initialized (it is not automatically opened), on the Add button is added a handler that opens a dialog, and on the Save push is added a handler that posts AJAX requests to the server-side page and sends a name that is entered. In the success handler of the AJAX call, the dialog is closed and the table is redrawn.
As a result, each time you post the form, you will see that the table is reloaded.
Case 5 - Filtering Using Grade Elements
Implementation of other cases of usage are similar to the 3 approaches described above. You can hands add some select dropdown, check boxes, or fifty-fifty the entire class that volition refresh the tabular array content.
All you volition need to practise is attach an event handler that volition phone call the fnDraw
function and inject parameters y'all want to send to the controller via an AJAX phone call in the fnServerData
settings in the initialization. When fnDraw
is chosen, the DataTables
plug-in volition send a new AJAX request, pass the parameters defined in fnServerData
, take results, and put them in the table. Therefore, I will non show implementations of other cases considering they are very similar.
If y'all want to refresh using the form elements that are directly related to the columns in the tabular array, there is an easier pick. You can use the jQuery DataTables ColumnFilter add-on that can add together course filters to the DataTable
. You can see how this form filter works if yous add together the filters in the columns or in the dissever form. This filter can exist applied either on the row data that are already populated in the tabular array or on the AJAXified tabular array. With this plug-in, you exercise not need to implement outcome handlers and an AJAX request. All you need to practice is to utilize a column filter plug-in on the DataTables plug-in configured in the server side fashion. An example of the code that initializes the columnfilter
plug-in with DataTables in the server-side processing style is shown in the post-obit listing:
$(' #employees').dataTable({ " bJQueryUI": truthful, " bServerSide": truthful, " sAjaxSource": " MasterDetailsAjaxHandler" }).columnFilter({ aoColumns: [ { type: " select"}, { type: " text" }, { type: " text" }, { blazon: " text" } ] });
This case adds a select list for filtering by commencement column and text boxes for filtering by other columns. If the DataTables plug-in is initialized in server-side fashion, filters volition also be sent to the server-side via AJAX calls. You tin can come across more than details virtually the column filter configuration on the jQuery DataTables ColumnFilter site.
The last required part of the example is a controller that will handle the requests.
Controller
The controller handles the asking sent from the browser and provides view/data that will be shown in the browser. Hither, the controller has two methods that handle a request:
- Load method that returns the view page when the page is loaded,
-
Employees
AJAX handler that returns the employees when jQuery DataTables sends the AJAX request. This activeness volition returnemployees
data when the jQuery DataTables plug-in wants to refresh the content, therefore it should accept standard parameters (current page, number of items per page, etc.) that ascertain the current view state of the table. However, to back up refreshing a table for a selected company (instance three above), in this controller activity is added the company ID parameter that will be used to additionally filter employees by company.
The first controller method is fairly simple. This method just returns the view that will be shown in the browser, as shown in the following listing:
public grade HomeController : Controller { public ActionResult Index() { render View(); } }
The 2d controller method is crucial - it returns the employees
for the employees
table. This method is shown in the following listing:
public class HomeController : Controller { public ActionResult MasterDetailsAjaxHandler( JQueryDataTableParamModel param, int? CompanyID) { var employees = DataRepository.GetEmployees(); var companyEmployees = (from e in employees where (CompanyID == null || due east.CompanyID == CompanyID) select eastward).ToList(); var filteredEmployees = (from east in companyEmployees where (param.sSearch == null || e.Name.ToLower().Contains(param.sSearch.ToLower())) select e).ToList(); var effect = from emp in filteredEmployees.Skip( param.iDisplayStart).Take(param.iDisplayLength) select new[] { Convert.ToString(emp.EmployeeID), emp.Proper name, emp.Position }; return Json(new { sEcho = param.sEcho, iTotalRecords = companyEmployees.Count, iTotalDisplayRecords = filteredEmployees.Count, aaData = result }, JsonRequestBehavior.AllowGet); } }
The name of the method must match the sAjaxSource
parameter set in the employees information table. This method accepts an object that encapsulates the parameters sent from the DataTables plug-in (current page, sort direction, number of items that should be displayed per page, etc.) More than details about the server side processing parameters can be plant in the get-go commodity in this serial. Besides this parameter, an additional parameter called CompanyID
is added in the method signature. This parameters is relevant simply for case iii and it is used to filter employees by the selected company ID. The proper noun of this parameter must match the proper noun of the parameter that is added in the fnServerData
function in case iii. The other lawmaking in the torso of the method just filters the employee information and returns it in JSON format equally it is expected past the jQuery DataTables plug-in. More than details nearly the server-side configuration can be found in the first article in this series.
Summary
This article shows how y'all can easily reload table content in ASP.NET MVC using the jQuery DataTables plug-in. Minimal code is required on the client-side, and on the server-side, we need standard processing functions. This plug-in allows you to create an constructive, AJAXified, Web 2.0 interface with minimal effort and straightforward implementation guidelines. You can download the case project implemented in ASP.NET MVC here.
Yous might likewise be interested in the other articles in this series showing:
- How to implement server-side processing in ASP.NET MVC with the jQuery DataTables plug-in
- How to implement a fully editable table in ASP.NET MVC with jQuery DataTables and several jQuery plug-ins that enable complete information direction functionality.
I promise these manufactures volition help you lot while implementing ASP.Internet MVC applications.
History
- 5th April, 2011: Initial version
Source: https://www.codeproject.com/articles/177335/refreshing-content-of-the-table-using-ajax-in-asp
Posted by: briggspretrusiona.blogspot.com
0 Response to "How To Reload And Update Mvc View Automatically When Inputs Change"
Post a Comment