Search code examples
c#asp.netgridviewtablednd

How to invoke function in asp.net using javascript?


I'm using the jquery plugin tablednd

$(document).ready(function () {
    $('#mygridview').tableDnD();
})

to make my rows in my gridview draggable. When I've dragged a row I want to invoke a function in asp.net to save the positions of the rows. But I can't find a proper event on gridview that only reacts on clicking on a row.

There is a onDrop method in tableDnd.

$(document).ready(function () {
    $('#mygridview').tableDnD({
      onDrop: function(table, row) {
   });
})

But how could I from there invoke a asp.net method? I've read some about ajax post but I don't understand that.

And I also read about using PageMethods but it didn't invoke my function.

The question is how can I write something that executes an update on a table in my database?

UPDATED:

I solved it using the IPostBackEventHandler method.

I had to extend both my user control and my page with IPostBackEventHandler and then added the public void RaisePostBackEvent(string eventArgument) function on both the user control and page. And finally:

onDrop: function (table, row) {
                __doPostBack('<%= this.UniqueID %>', 'Select');
            }

If someone got problem with onDrop, the solution is you have to give ID to each row like this:

    var i = 0;
    $("#<%= gridviewID.ClientID %>").find('tr').each(function () {
        $(this).attr('id', i++);
    });

above the initiation of the tablednd.

Thanks!


Solution

  • There are two ways in general, one using AJAX and second, using postbacks.

    The AJAX way:

    1. Add ScriptManager to the page, like this:

      <asp:ScriptManager runat="server"
             ID="ScriptManager1" 
             EnablePageMethods="true"
             EnablePartialRendering="true"
      />
      
    2. Make the server side method to be called as public static. Also mark it with the System.Web.Services.WebMethod attribute, like this:

      [WebMethod]
      public static string DoServerStuff(string parameter)
      {
          return "Parameter passed: " + parameter;
      }
      
    3. Call it from the client side, via the PageMethods class, like this:

      function doClientStuff() {
          var result = PageMethods.DoServerStuff('test parameter');
          alert(result);
      }
      
    4. For doing the same thing using jQuery check this out.


    The postbacks way:

    1. Make the page (that contains the method to be called) implement the IPostBackEventHandler interface.
    2. Call the __doPostback method on the client side, like this:

      function doClientStuff() {
          var result = __doPostBack('<%= this.UniqueID %>', 'Select');
      }
      
    3. Implement the server side logic inside the IPostBackEventHandler.RaisePostBackEvent method of the page.

    4. More on the raising postbacks from the client side here.