Vous êtes sur la page 1sur 14

17/02/2019 Implement jQuery Datatable in ASP.

NET MVC application | DotNet - awesome

Dotnet Awesome HOME ASP.NET MVC JQUERY ANGULAR

Implement jQuery Datatable in ASP.NET MVC


application
Friday, November 20, 2015 sourav mondal DataTable | grid | Jquery | jQuery DataTable | MV

Part 1 - Implement jQuery Datatable in ASP.NET MVC application.

Introduction
Here in this article, we will see how to Implement jQuery Datatable in ASP.NET MVC application
DataTables is a most powerful and easy to use jQuery plugin for display tabular data (table list
with support for Pagination, searching, State saving, Multi-column sorting with data type dete
and lots more with ZERO or minimal configuration. Most important It is open source.

Do you have AngularJS application? Please visit datatables in AngularJS and asp.net mvc in or
implement datatables in angular application.

Before this article, I have explained How to use Telerik Grid in MVC4 application , How to displa
database data in webgrid in mvc and more about gridview for display tabular data in our applic

http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 1/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome

Dotnet Awesome HOME ASP.NET MVC JQUERY ANGULAR


Here we will see followings with ASP.NET MVC as server side...
1. Part 1: Implement jQuery Datatable (Basic initialization) in ASP.NET MVC application.
2. Part 2: jQuery Datatable server side pagination and sorting in ASP.NET MVC
3. Part 3: Implement custom multicolumn server-side filtering in jQuery dataTables
4. Full CRUD operation using datatables in ASP.NET MVC
5. Next article coming soon...

DataTables is very easy to use. We just need to add 1 CSS file, and 1 js file and 3 lines of jqu
code as below to start.
1. //cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css
2. //cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js
3. <script>
4. $(document).ready(function () {
5. $('#myTable').DataTable();
6. });
7. </script>
8.

you can check the below code...


1. <html>
2. <head>
3. <link rel="stylesheet" type="text/css" href="http://cdn.datatab
4. </head>
5. <body>
6. <div style="width:400px; margin:0 auto">
7. <table id="myTable" >
8. <thead>
9. <tr><th>Country</th></tr>
10. </thead>
11. <tbody>
12. <tr><td>India</td></tr>
13. <tr><td>UK</td></tr>
14. <tr><td>USA</td></tr>
15. </tbody>
16. </table>
17. </div>
18. <script type="text/javascript" charset="utf8" src="http://ajax.
19. <script type="text/javascript" charset="utf8" src="http://cdn.d
20. <script>
21. $(function(){
22. $("#myTable").dataTable();
23. })
24. </script>

But it will be useful when I will fetch data from server side for display in jQuery DataTable. So,

http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 2/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome

we will see How to fetch data from server side and display in jQuery DataTable.
Dotnet Awesome HOME ASP.NET MVC JQUERY ANGULAR

Just follow the following steps in order Implement jQuery Datatable (Ba
initialization) in ASP.NET MVC application.

Step-1: Create New Project.


Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name >
OK > Select Basic > Select view engine Razor > OK

Step-2: Add a Database.


Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Ser
Database Under Data > Enter Database name > Add.
Here I have added a database for store some location information in our database for show in
google map.

Step-3: Create a table.


Here I will create 1 table (as below) for store data.
Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table n
> Ok.
In this example, I have used 1 table as below

Step-4: Add Entity Data Model.


Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New ite
Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Nex

http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 3/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome

Chose your data connection > select your database > next > Select tables > enter Model
Dotnet Awesome HOME ASP.NET MVC JQUERY ANGULAR
Namespace > Finish.

Step-5: Create a Controller.


Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add >
Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller "HomeController"

Step-6: Add new action into the controller to get the view where we will
implement jQuery DataTable
Here I have added "Index" Action into "Home" Controller. Please write this following code
1. public ActionResult Index()
2. {
3. return View();
4. }
5.

Step-7: Add view for the action (here "Index") & design.
Right Click on Action Method (here right click on Index action) > Add View... > Enter View Nam
Select View Engine (Razor) > Add.
Complete HTML code
1. @{
2. ViewBag.Title = "Index";
3. }
4.
5. <h2>Part 1 : Implement jQuery Datatable in ASP.NET MVC</h2>
6. <div style="width:90%; margin:0 auto;">
7. <table id="myTable">
8. <thead>
9. <tr>
10. <th>Employee Name</th>
11. <th>Company</th>
12. <th>Phone</th>
13. <th>Country</th>
14. <th>City</th>
15. <th>Postal Code</th>
16. </tr>
17. </thead>
18. </table>
19. </div>
20. <style>
21. tr.even {
22. background-color: #F5F5F5 !important;
23. }

http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 4/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome

Dotnet Awesome HOME ASP.NET MVC JQUERY ANGULAR

Step-8: Add another action (here "loaddata") for fetch data from the
database.
1. public ActionResult loaddata()
2. {
3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
4. {
5. // dc.Configuration.LazyLoadingEnabled = false; // if your table is r
6. var data = dc.Customers.OrderBy(a => a.ContactName).ToList();
7. return Json(new { data = data }, JsonRequestBehavior.AllowGet);
8. }
9. }
10.

Step-9: Run Application.


Yahoooooo! We have done.... BUT here in this article we fetched all the data from server at on
done pagination, sorting, instant searching at client side. This can be a performance issue fetc
large amount of data from server side at once. To resolve this performance issue, we can integ
server-side pagination, sorting and searching. In the next article, I have implemented jQuery
DataTable server side pagination and sorting in ASP.NET MVC application

DOW NLOAD & LIVE DEMO

http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 5/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome

Dotnet Awesome HOME ASP.NET MVC JQUERY ANGULAR

PREVIOUS NEXT
Creating Google Maps Sample App with AngularJS jQuery Datatable server side pagination and sor
and asp.net MVC in ASP.NET MVC

sourav mondal

Hello ! My name is Sourav Mondal. I am a software developer working in Micr


.NET technologies since 2010.

I like to share my working experience, research and knowledge through my s

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc,


winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

RELATED POSTS:

IMPLEMENT CUSTOM JQUERY DATATABLE SERV ER SIDE FULL CRUD OPERATION US


MULTICOLUMN SERV ER-SIDE PAGINATION AND SORTING IN DATATABLES IN ASP.NET
FILTERING IN JQUERY... ASP.N...

39 Comments Dotnetawesome 
1 Lo

 Recommend 5 t Tweet f Share Sort by

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 6/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome

Dotnet Awesome
jagadeesh kumar • a year ago
HOME ASP.NET MVC JQUERY ANGULAR

HI,I am getting data into view but paging and sorting are not applying to my page plz help me
△ ▽ • Reply • Share ›

Karayanni • a year ago


Hi,
I have a webServes that returns a DatatTable tbl;
how to I return the datatable to the Ajax call?

I tried some thing like the code bellow but does not work
DataTable dtTemp = new DataTable();
List<dictionary<string, object="">> rows = new List<dictionary<string, object="">>();
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object=""> row;
dtTemp = tbl.Clone();
foreach (DataRow dr in tbl.Rows)
{
row = new Dictionary<string, object="">();
foreach (DataColumn col in tbl.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}

var data = serializer.Serialize(rows);


return Json(new { data = data }, JsonRequestBehavior.AllowGet);
△ ▽ • Reply • Share ›

Dolly Dollz • a year ago


I have getting the error like below.,
System.Globalization.CultureInfo
I am not using entity framework code.,
the below is how my code is written.,

using (MySqlConnection con = new MySqlConnection(constr))


{
con.Open();
MySqlCommand cmd = new MySqlCommand("Select
ContactName,CompanyName,Phone,Country,City,PostalCode from CustomerInfo Order By
ContactName",con);
DataSet ds = new DataSet();
MySqlDataAdapter part1da = new MySqlDataAdapter(cmd);
part1da.Fill(ds);
return Json(new { ds = ds }, JsonRequestBehavior.AllowGet);
}

After execution of all lines i have getting error like below


A circular reference was detected while serializing an object of type
http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 7/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome
A circular reference was detected while serializing an object of type
Dotnet Awesome
'System.Globalization.CultureInfo'. HOME ASP.NET MVC JQUERY ANGULAR

Please do reply at the earliest.Thanks in advance :)


△ ▽ • Reply • Share ›

souravmondal45 Mod > Dolly Dollz • a year ago


try this code to convert to json result
JsonConvert.SerializeObject(myObject, Formatting.Indented,
new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
})
△ ▽ • Reply • Share ›

Dolly Dollz > souravmondal45 • a year ago


when i use the above code i get error because as Json converter is of string type
am using JsonResult/actionResult as my return type so getting error.Please sug
△ ▽ • Reply • Share ›

Charly López • a year ago


Any one else got: "Failed to load resource: the server responded with a status of 500 (Internal S
Error) loaddata?_=1508949018930" ?
△ ▽ • Reply • Share ›

Özgür Sarıkamış • 2 years ago


thank you. it helped me a lot
△ ▽ • Reply • Share ›

Mohammed Rehan Javed Abdul Kar • 2 years ago


HI Sourav,

I am trying to load datatable on button click using jquery:

I am passing parameters and loading data but the data is not rendering into the datatable

My code is given below:

$(document).ready(function () {
$('#btnSearch').click(function () {
debugger;
loader()
});

function loader() {
$('#ReportDT').DataTable({
"ajax": {
"url": '@Url.Action("GetTransactions", "Report")',
"data": {
$ $
see more

△ ▽ • Reply • Share ›
http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 8/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome

Dotnet Awesome
Marjorie Espejo • 2 years ago
HOME ASP.NET MVC JQUERY ANGULAR

Hi! Thank you for this very useful tutorial. Likewise, I have error encountered on javascript. Can
help me with these problem?
Thank you in advance.


△ ▽ • Reply • Share ›

DrKashyap Ajay • 2 years ago


sourav mondal Sir i am Also Trying to implement DataTable But i Am not Able To fetch foreign ke
value. Can u plz help me how to solve it
△ ▽ • Reply • Share ›

sahaya alex • 2 years ago

△ ▽ • Reply • Share ›

souravmondal45 Mod > sahaya alex • 2 years ago


please check you have added the datatable jquery library....
△ ▽ • Reply • Share ›

sahaya alex > souravmondal45 • 2 years ago


That issue occurred due to conflict of library file sir
△ ▽ • Reply • Share ›

sahaya alex • 2 years ago


i am getting below issue

sections have been defined but have not been rendered for the layout page
△ ▽ • Reply • Share ›

souravmondal45 Mod > sahaya alex • 2 years ago


check in your layout page.

add this if not already added


@RenderSection("scripts", required: false) below the jquery library
△ ▽ • Reply • Share ›

james • 2 years ago


http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 9/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome
james • 2 years ago

Dotnet
CanAwesome
you do an example that includes edit save and delete
HOME records.
ASP.NET MVC JQUERY ANGULAR

△ ▽ • Reply • Share ›

souravmondal45 Mod > james • 2 years ago


Yes I will. Thanks for visit my blog.
△ ▽ • Reply • Share ›

james > souravmondal45 • 2 years ago


Thank You
△ ▽ • Reply • Share ›

Vijay Detwal • 2 years ago


Actully sir i while projact selecting i was select EMpty mvc application that'swhy its give me erro
now i choose basic now its working fine but my question is what change should i make in layou
so it will working fine
△ ▽ • Reply • Share ›

Vijay Detwal • 2 years ago


hello sir i am getting one error that is
The following sections have been defined but have not been rendered for the layout page
"~/Views/Shared/_Layout.cshtml": "Scripts".
please give me response as soon as possible
△ ▽ • Reply • Share ›

souravmondal45 Mod > Vijay Detwal • 2 years ago


It means that you have defined a section in your master Layout.cshtml, but you have not
included anything for that section in your View.

add this line in your view page

@section scripts{
// Add something here
}
△ ▽ • Reply • Share ›

FP00 • 3 years ago


The ObjectContext instance has been disposed and can no longer be used for operations that r
a connection. when i run it
△ ▽ • Reply • Share ›

souravmondal45 Mod > FP00 • 3 years ago


do you have relationship properties? if yes please disable lazy loading with the below line
code.
dc.Configuration.LazyLoadingEnabled = false;

if no, please check your query once, have you executed your query before return?
△ ▽ • Reply • Share ›

mistry jayendra • 3 years ago


http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 10/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome
st y jaye d a 3 yea s ago
when
Dotnet i use this code it will print data but not display inHOME
Awesome table format data,i
ASP.NET MVCam used VS2010
JQUERY ,i wa
ANGULAR
attach here screen shot like below how to solved this and also attach my code with Controller M
And View Codeayendra mistryj


△ ▽ • Reply • Share ›

souravmondal45 Mod > mistry jayendra • 3 years ago


i can see that you have opened localhost:61255/home/userlist12 in your browser instead
localhost:61255/home/userlist3.
△ ▽ • Reply • Share ›

Vipin Bhandari • 3 years ago


can you send main a project with angularjs data table using server side processing using asp.n
web api for server side processing? thnx .
△ ▽ • Reply • Share ›

souravmondal45 Mod > Vipin Bhandari • 3 years ago


you can check this out http://www.dotnetawesome.co...

just replace dtOption url with your webapi service url.


△ ▽ • Reply • Share ›

Serkan • 3 years ago


datatables warning:table id=myTable-Ajax error , how can we fix this ?
△ ▽ • Reply • Share ›

souravmondal45 Mod > Serkan • 3 years ago


can you please share your code?
△ ▽ • Reply • Share ›

Serkan > souravmondal45 • 3 years ago


http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 11/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome
Serkan > souravmondal45 3 years ago

Dotnet Awesome
Same codes on the above. HOME ASP.NET MVC JQUERY ANGULAR

△ ▽ • Reply • Share ›

Venkat Kiran Kumar Chowdary • 3 years ago


hi guys please help me any one,how to add hyperlinks in jquery data table
△ ▽ • Reply • Share ›

souravmondal45 Mod > Venkat Kiran Kumar Chowdary • 3 years ago


Hi, you can add link with this render property...

"columns": [
{ "data": "Country", "autoWidth": true },
{
"data": "CustomerID",
"render": function (data, type, full, meta) {
return 'Edit';
}
}
]
△ ▽ • Reply • Share ›

Velkumar Santhanaraj > Venkat Kiran Kumar Chowdary • 3 years ago


{"sName": "Firstnames", "bSearchable": true, "mRender": function (data, type, full) {
return '' + data + '';}},
△ ▽ • Reply • Share ›

Naviya Nair • 3 years ago


This comment has been removed by the author.
△ ▽ • Reply • Share ›

Naviya Nair • 3 years ago


This comment has been removed by the author.
△ ▽ • Reply • Share ›

Karma Yuta • 3 years ago


HI Bro, saw your tutorial realy great. then i try to do the same. notg change on codes. but when
im facing this issue. Kindly advice me and help me. thanks.


△ ▽ • Reply • Share ›

Charly López > Karma Yuta • a year ago


// **** UNCOMENT THIS LINE IN THE CONTROLLER dc.Configuration.LazyLoadingEn
= false; // if your table is relational, contain foreign key
var data = dc.Estados.OrderBy(a => a.EstadoId).ToList();
return Json(new { data = data } JsonRequestBehavior AllowGet);
http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 12/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
Dotnet Awesome
△ ▽ • Reply • Share › HOME ASP.NET MVC JQUERY ANGULAR

Daniel N. (Nyro) > Karma Yuta • 3 years ago


You can try changing the javascript "url": "/home/loaddata" by "url": "@Url.Action("loadda
This error typically occur when the server responds with anything other than a 2xx HTTP
status code. Check the status response using F12 (or Firebug in FireFox)
△ ▽ • Reply • Share ›

Rawan > Daniel N. (Nyro) • a year ago


also same error "url": "@Url.Action("loaddata")" is not fix it
△ ▽ • Reply • Share ›

ALSO ON DOTNETAWESOME

Event/Scheduler calendar in asp.net MVC Part 2 : Token Based Authentication Usi


application | DotNet - awesome ASP.NET Web API in AngularJS | DotNet
11 comments • 2 years ago 12 comments • 2 years ago
sujith — can i create 2 events in same day, i am Vikas Tyagi — Hi Sourav MondalFirst of al
getting Primary key error what to thank to you for such a valuable a
it really help me out.i am new to web api a

Angular 2 components | DotNet - awesome Import Excel Sheet Data in MS SQL serv
1 comment • 2 years ago Database using AngularJS | DotNet - …
VINAY KUMAR GUPTA — Nice article please 3 comments • 2 years ago
publish angular 2 with web api integration Mujahid Hussain — Dear Sir,Hope you are
only uploads 200 rows. is there in way to
increase the rows records.

✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy

FEAT URED POST LABELS

Event/Scheduler calendar in asp.net MVC (70) JQUERY (47) GRID (24) ANGULARJS (2

MVC application GRIDVIEW (20) REPORT (14) WEBGRID (14)

SAVE DATA (12) EXPORT (11) FILE UPLOAD (11)


Introduction Today I will show you, how to
GOOGLE CHART (10) RET RIVE DATA (10) CRUD (7)
implement Event/Scheduler calendar in asp.net MVC
application. We know that Modern w... ENT RY FORM (7) MAST ER-DETAILS (7) VALIDAT ION

http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 13/14
17/02/2019 Implement jQuery Datatable in ASP.NET MVC application | DotNet - awesome

Dotnet Awesome WEB API (7)


HOME
ANGULAR 2 (7)
ASP.NET MVC
CHART (7)
JQUERY ANGULAR

ENT IT Y FRAMEWORK (6) BULK INSERT (5) LOGIN P

JQUERY DATATABLE (5) PAGING (5) AUT OCOMPLE

CASCADE DROPDOWN (4) CUST OM FORM AUT HENT IC

DATATABLE (4) FORM AUT HENT ICAT ION (4)

POST MET HOD (4) REACT JS (4) FULLCALENDAR (4

IMPORT (4) MODEL POPUP (4) RDLC (4)

REGIST RAT ION PAGE (4) T REEVIEW (4) DELET E D

GOOGLE MAP (3) HT T P CLIENT (3) MULT ILINGUAL

CAPT CHA (3) GOOGLE RECAPT CHA (3) DATA ANNO

GENERIC HANDLER (2) ANGULARJS DATATABLE (2)

SCHEDULAR (2) CRYSTAL REPORT (1) ROLE PROV

STAR RAT ING SYST EM (1) T ELERIK (1)

COPYRIGHT © 2015 DOTNET - AWESOME

http://www.dotnetawesome.com/2015/11/implement-jquery-datatable-in-aspnet-mvc.html 14/14

Vous aimerez peut-être aussi