Wednesday, 13 January 2016

Binding data from database to table using JQuery datatable's plugin in ASP.NET MVC


  • JQuery provides a plugin through which one can display data from database to your web application.
  • Let's see how?
  • Goto JQuery datatables.net and copy the css and JS from there and add to your page.





  • F






























  • First of all let us see how to access the data from database to application.
  • Here we'll use Json and ajax request for displaying the data and we'll get the data from database using WebService.
  • First of All create a database and install entity framework in your application through nuget.
  • Create a model for working with database as shown.

  • Now create a Web Service first that will return the data in Json format.
  • Create a service named  and a Web Method  as shown in below figure.

























































  • Here above JavaScriptSerializer(Serialize) is used to return the data in Json format.
  • Run this service you should see the data in Json format something like this as shown below.
  •  






















  •  (* Note you should have added the css and JS which I described before for the reference to JQuery DataTables and CSS)
  • Add headers to the table as shown.























  • Now write the script as shown in figure below.








































  • Let me explain you what is exactly done above.
  • As you can see we have given reference for JQuery, Datatables.min.css & DataTables.min.js.
  • Now coming to <script> portion.
  • We are calling the webservice as shown through url parameter of ajax.
  • DataType we used is Json because the data we'll consume would be in Json.
  • Now on success let us define a parameter called 'data', on tableid='datatable' selector provide property to dataTable attribute of JQuery DataTables plugin '('#datatable').dataTable()'.
  • Now data to that plugin datatable we would provide is our data parameter on success('data:data').
  • There after just bind the column names of database with the data as shown.
  • After binding if you have given the date as datatype in db then you wouldn't see date for that some script need to be changed and return the date by rendering the date in a proper way as shown above.
  • Similarly  if you want to display currency before salary then as shown in fig for Mobile '(M)' can be done easily.
  • This is how to use the JQuery DataTables.net in a simple way.



No comments:

Post a Comment

How To Pass An Array As A Parameter While Calling an ASP.NET Web API C#

Please visit my C# Corner Blog for this, where I have provided better efforts to make this concept more understandable - www.c-sharpcorner....