ASP.net Grid View with jQuery Ajax (Dynamic Load for ASCX HTML)


After a couple of months without touching anything related to WEB. I’m doing some refreshment by creating Web Diagram Tool using jQuery “Something like Visio on WEB”.

Also my brother asked me to help to him to do a paging using AJAX.

I found some articles that used Update Panel …Yuk!!! .. Come-on people! are you still use it!! Update Panel could be useful sometimes. But its not a full AJAX. It will create a request for the whole page and when response comes back; It will refresh the part which in update panel.

I did something deferent and better. Its not new at all. Actually I worked on this task before a couple of years; I’m doing some refreshment, my brother just triggered me when he ask.

Simply, I loaded the Usercontrol  dynamically. and the Usercontrol contains anything you want (in my case it’s a GridView). Tada! pretty easy.

to load controls dynamically use this static method. I you want to use it; just modify it by adding your control and set your own properties.

private static String GetGridControlContent(String controlLocation,
 int pgIndex, int pgSize)
 {
   var page = new Page();

   var userControl = (MyGridView)page.LoadControl(controlLocation);

   if (pgIndex < 0)
         pgIndex = 0;

   userControl.PageSize = pgSize;
   userControl.PageIndex = pgIndex;

   page.Controls.Add(userControl);

   String htmlContent = "";

   using (var textWriter = new StringWriter())
   {
    HttpContext.Current.Server.Execute(page, textWriter, false);
    htmlContent = textWriter.ToString();
   }
   return htmlContent;
 }

 

As you see above; you can pass any parameter to the Usercontrol by creating a properties in that user control. For me I created PageSize & PageIndex properties.

You can wrap this method in a web method to call it from Javascript.

[WebMethod]
public static string AjaxGetGridCtrl(int pgIndex, int pgSize)
{
     return GetGridControlContent("~/MyGridView.ascx", pgIndex, 
                                  pgSize);
}

 

So you can load you control using script mnager or using jQuery AJAX library. I used the 2nd choice

$.ajax({
    type: 'POST',
    url: 'MyDefault.aspx/AjaxGetGridCtrl',
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data) {
       $('#mainDiv').html(data.d);
    },
    data: "{pgIndex:'" + pgIndex + "', pgSize:'" + pgSize + "'}"
 });

 

 

jQuery AJAX is really nice. Let’s talk more about the options above.

type: you choose you either GET, or POST options.

url: I request this URL using POST.

contentType: used when you want to send data to the server (data is the last option). is this case the data will be sent in JSON format with UTF-8 Encoding.

dataType: The type of data that you’re expecting back from the server.

success: response will be handled here; if request succeeded.

I n this example; the HTML result will be rendered in mainDiv element.

data: parameters will be sent to the web method here.

Current Page Index and Page Size are stored in a Hidden Fields. And when user clicked on Next button; the value will be added by 1. And the AJAX call started by sending the new PageIndex.

 

function FillGrid(flag) {

 var pgIndex = 0;
 var pgCurrentIndex = $('#txtPgIndex').attr('value');
 var pgSize = $('#txtPgSize').attr('value');

 switch (flag) {
      case 'prev':
          pgIndex = parseInt(pgCurrentIndex) - 1;
          break;
      case 'next':
          pgIndex = parseInt(pgCurrentIndex) + 1;
                    break;
            }

            $('#txtPgIndex').attr('value',pgIndex);

      $.ajax({
           type: 'POST',
           url: 'MyDefault.aspx/AjaxGetGridCtrl',
           contentType: "application/json; charset=utf-8",
           dataType: 'json',
           success: function (data) {
               $('#mainDiv').html(data.d);
           },
           data: "{pgIndex:'" + pgIndex + "', pgSize:'" + pgSize + "'}"
       });
    }

 

Calling GetGridControlContent will cause a crahs at this line

 
HttpContext.Current.Server.Execute(page, textWriter, false);
 
 
To avoid this crash; all you need to do is to add
a [run at server form tag] to your Usercontrol
 
 
<%@ Control Language="C#" AutoEventWireup="true" 
    CodeBehind="MyGridView.ascx.cs" 
    Inherits="test.MyGridView" %>
<form id="form1" runat="server">
<asp:GridView ID="gv" runat="server" AllowPaging="true" 
              AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="ID" 
               HeaderText="First Name" Visible="false" />
        <asp:BoundField DataField="FirstName" 
               HeaderText="First Name" />
        <asp:BoundField DataField="LastName"
               HeaderText="Last Name" />
        <asp:BoundField DataField="Mobile" 
               HeaderText="Mobile" />
        <asp:BoundField DataField="EmpSalary" 
               HeaderText="Salary" />
        <asp:BoundField DataField="HiringDate" 
               HeaderText="Hiring Date" />
        <asp:BoundField DataField="DOB" 
               HeaderText="Date of Birth" />
    </Columns>
</asp:GridView>
<div id="pgingFooter">
    <a href="javascript:void(0);" id="prev">Previous</a> 
        &nbsp;|&nbsp; <a href="javascript:void(0);"
        id="next">Next</a>
</div>

</form>

 

And there is no magical things in the code behind for this user control, Just fill your GridView Control according to PageIndex & PageSize properties.

public partial class MyGridView : System.Web.UI.UserControl
    {
        private List<Employee> lstEmployees;

        public int PageSize { get; set; }
        public int PageIndex { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            lstEmployees = new List<Employee>();

            FillList();
            lstEmployees = 
                       lstEmployees.Skip(this.PageIndex * this.PageSize)
                                   .Take(this.PageSize).ToList();

            gv.DataSource = lstEmployees;
            gv.DataBind();
        }

        private void FillList()
        {
            for (int j = 1; j <= 100; j++)
            {
                lstEmployees.Add(new Employee { 
                     ID = j, FirstName = "First" + j, 
                     LastName = "Last" + j, 
                     Mobile = "+932 55 1212" + j, 
                     EmpSalary = j * 100, 
                     DOB = "12/12/1990", 
                     iringDate = "12/12/2010" });
            }
        }
    }

 

You can download the sample from here

Advertisements

11 thoughts on “ASP.net Grid View with jQuery Ajax (Dynamic Load for ASCX HTML)

  1. vvvlad says:

    Thanks for a great and helpful article.
    One question: how about running some jquery on the user control?
    Where should the reference added (on UC or the hosting page)?

    • I prefer to add it in a separate javaScript file call it for ex. ==> myUserControl.js
      Then add your document.ready there and anything related to the user control.
      And add it to your host page
      Let say:

      var myUserControlManager = function() {

      var self = this;
      self.goPrevious = function() {
      // Your Code Here
      };
      self.goNext = function() {
      // Your Code Here
      };
      self.goToPage = function(pageIndex) {
      // Your Code Here
      };

      // Add your jQuery stuff here
      $(function() {

      });

      };

      // Now you can use this variable any where
      var myUserControlMan = new myUserControlManager();

      • vvvlad says:

        Thanks again!
        I’m actually stuck referencing the javascript file in UC. What I mean is that I’ve tried numerous ways to reference the .js file, but nothing works, no code executed from those files (I just call alert(“test”) for checking that).
        I only to manage to run javascript from the on ascx file.

      • Ok, i did not tried that before. But I think its better to execute your jQuery code when jQuery Ajax completed; so your grid will be rendered on DOM then execute your code.
        So as you see in my example (download it from above link) you can execute your jQuery code in success callback after this line of code:

        $(‘#mainDiv’).html(data.d);

        I prefer not to execute my JS stuff in the response. Actually i’m wondering what is jQuery code will do? Could you please tell me and maybe that will let me help you better.

  2. Rashid Siddiqui says:

    you should have use:
    $(‘#mainDiv’).html(“”);

    before

    $(‘#mainDiv’).html(data.d);

    in the code. If you don’t, on every page index change, another instance of grid renders and html again write in the “mainDIv” instead of just refreshing the existing grid.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s