Abhishek Ghosh
Abhishek Ghosh

Reputation: 2706

jQuery DataTable JS not working(ASP .NET 3-tier architecture)

I am using a 3-tier architecture in my project, which has the following structure :

  1. Web Pages(has reference to BusinessLogic(C# Class)
  2. Business Logic(has reference to the DataAccess(C# class) contains all the methods for data access.
  3. DataAccess - contains methods for database operations(Insert,Update,Delete,etc)

Now in my website, I am using a MasterPage-ContentPage relationship. As I have learned I am loading all my scripts and CSS for the individual pages in my master page.

Here is my bottom section(scripts references) of the Master Page :

 <!-- jQuery 2.1.4 -->
    <script type="text/javascript" src="../../plugins/jQuery/jQuery-2.1.4.min.js"></script>

    <!-- Bootstrap 3.3.2 JS -->
    <script src="../../bootstrap/js/bootstrap.min.js" type="text/javascript"></script>

    <!-- SlimScroll -->
    <script src="../../plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>

    <!-- FastClick -->
    <script type="text/javascript" src='../../plugins/fastclick/fastclick.min.js'></script>

    <!-- AdminLTE App -->
    <script src="../../dist/js/app.min.js" type="text/javascript"></script>

    <script src="dist/js/toastr.js" type="text/javascript"></script>

    <!-- Demo -->
    <script src="../../dist/js/demo.js" type="text/javascript"></script>

    <!-- DATA TABES SCRIPT -->
    <script type="text/javascript" src="media/js/jquery.dataTables.js"></script>
    <script type="text/javascript">
        $('#example').dataTable();
    </script>

Here is the top section(CSS references) of my master page :

 <!-- Bootstrap 3.3.4 -->
    <link href="../../bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <!-- Font Awesome Icons -->
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
    <!-- Ionicons -->
    <link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css" />

    <!-- Theme style -->
    <link href="../../dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />
    <link href="dist/css/toastr.css" rel="stylesheet" type="text/css" />

    <link href="media/css/jquery.dataTables.css" rel="stylesheet" />

    <!-- AdminLTE Skins. Choose a skin from the css/skins 
         folder instead of downloading all of them to reduce the load. -->
    <link href="../../dist/css/skins/_all-skins.min.css" rel="stylesheet" type="text/css" />

As I have seen from the official jQuery DataTable tutorial page, this is the way I should initialize my DataTable in my script.

Still when I run the CSS works as expected, but the JS doesn't work as I tried to use the functions like sorting,searching,etc. - NOTHING WORKS.

This is my content page for reference :

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="content-wrapper">
        <div class="content">
            <div class="box">
                <div class="box-header">
                    <h3 class="box-title">Products : </h3>
                </div>
                <div class="box-body">
                    <asp:Repeater ID="rptr" runat="server">

            <HeaderTemplate>
                <table id="example" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th >Sr. No</th>
                            <th>Name</th>
                            <th>Category</th>
                            <th>Company</th>
                            <th>Price</th>
                            <th>In Stock</th>
                            <th>Min. Qty</th>
                            <th>Date Created</th>
                            <th></th>
                        </tr>
                    </thead>
            </HeaderTemplate>
            <ItemTemplate>
                <tbody>
                    <tr>
                        <td><%# Container.ItemIndex + 1 %></td>
                        <td><%# Eval("ProdName") %></td>
                        <td><%# Eval("CategoryName") %></td>
                        <td><%# Eval("CompanyName") %></td>
                        <td><%# Eval("ProdPrice") %></td>
                        <td><%# Eval("QuantityInStock")%></td>
                        <td><%# Eval("MinQuantity")%></td>
                        <td><%# Eval("DateCreated")%></td>
                        <td><a href='<%# "ProductDetails.aspx?ID=" + Eval("ProductID") %>'>View</a></td>
                    </tr>
                </tbody>
            </ItemTemplate>

            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>
                </div>
            </div>
        </div>
    </div>
</asp:Content>

and this is my PageLoad method. There are no other methods for the Page except PageLoad :

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["user"] != null)
            {
                rptr.DataSource = new ProductLogic().fillProductTable();
                rptr.DataBind();
            }
            else
            {
                Response.Redirect("Login.aspx?url=ProductDetails.aspx");
            }
        }
    }

I do not know what am I doing wrong. The data is being loaded correctly, the CSS is but the JS doesn't work at all. What is wrong that I am doing here ?

Upvotes: 0

Views: 1035

Answers (1)

Abhishek Ghosh
Abhishek Ghosh

Reputation: 2706

I believe there is ufcourse some way other than I am mentioning in my answer to use the jQuery DataTable in your ASP.NET web-application. But I found this the easiest way possible.

Step-1) Create a web service in your website.In the code below I am converting a datatable returned from my query result into a JSON Array with one of the utilities I found on the internet. Here is the code for the WebService :

/// <summary>
/// Summary description for ProductDetailsWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class ProductDetailsWebService : System.Web.Services.WebService
{
    [WebMethod]
    public void GetProductDetails()
    {
        ProductLogic prodLogic = new ProductLogic();
        DataTable dt = prodLogic.fillProductTable();

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();

        Dictionary<string, object> row;

        foreach (DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
        Context.Response.Write(serializer.Serialize(rows));
    }


}

Step-2) The HTML looks something very simple with a basic <thead> tag containing several <tr>. Note the id you give here is important as this id will be used in JS to find the table element. Here is the HTML :

<table id="datatable" class="table table-bordered table-striped">
       <thead>
          <tr>
             <th>Name</th>
             <th>Category</th>
             <th>Company</th>
             <th>Price</th>
             <th>In Stock</th>
             <th>Min. Qty</th>
             <th>Date Created</th>
             <th>More</th>
           </tr>
         </thead>
   </table>

Step-3) The JS :

<!-- DATA TABES SCRIPT -->
    <script type="text/javascript" src="media/js/jquery.dataTables.js"></script>
    <script type="text/javascript">
        $.ajax({
            url: 'ProductDetailsWebService.asmx/GetProductDetails',
            method: 'post',
            dataType: 'json',
            success: function (data) {
                var dataTableInstance = $('#datatable').dataTable({
                    data: data,
                    'scrollY': 300,
                    columns: [
                        { 'data': 'ProdName' },
                        { 'data': 'CategoryName' },
                        { 'data': 'CompanyName' },
                        {
                            'data': 'ProdPrice',
                            'render' : $.fn.dataTable.render.number(',', '.', 0)
                        },
                        { 'data': 'QuantityInStock' },
                        { 'data': 'MinQuantity' },
                        {
                            'data': 'DateCreated',
                            'render': function (jsonDate) {
                                var date = new Date(parseInt(jsonDate.substr(6)));
                                var month = date.getMonth() + 1;
                                return date.getDate() + "/" + month + "/" + date.getFullYear();
                            }
                        },
                        {
                            'data': 'ProductID',
                            'searchable' : false,
                            'sortable' : false,
                            'render': function (productID) {
                                return '<a href="ProductDetails.aspx?ID='+ productID +'">Full Details...</a>';
                            }

                        }
                    ]
                });
            }
        });
    </script>

NOTE: You need to have only the CSS and the JS for datatable which can be found at the jQuery Datable Tutorial Page.

Very Important Video tutorial for the same can be found at Kudvenkat's jQuery Tutorial series on YouTube.

Upvotes: 1

Related Questions