0

After a page is loaded I call some ajax methods, where some html elements are created, for example

$.ajax({
       ...
       success: function (data) {
          ...
          var myCoolLink = $("<a/>").attr('id', 'xyz')
                            .attr('onclick', 'doStuff()')
                            .appendTo(someOtherElement);
       }
});

The problem is that when myCoolLink is clicked, I want it to fire someFunction (with some arguments) in codebehind so that I can retrieve data to update a grid next to it.


Possible solutions and their problems:

  1. Change it to a LinkButton and add CommandArgument

CommandArgument is a server-side property, changing it won't mean a thing to the page.

  1. Add __doPostBack() in myCoolLink

Well, it will postback, but as I can't add runat="server" in my link (the same reasoning from the possible solution above) it won't do much besides this


The more I think about it the more I'm convinced this isn't possible. Either way, workarounds to my problem are always welcome! Looking forwards to your answers (:

Pretzel
  • 103
  • 5
  • You can pass a parameter along with __doPostBack(). If you need multiple parameters, you could bundle them in a JSON string like this: https://stackoverflow.com/questions/14482939/javascript-multiple-parameters-in-dopostback – Turnip May 25 '20 at 15:05
  • Or, you could use a WebMethod called from JavaScript and avoid the postback altogether. – Turnip May 25 '20 at 15:08
  • @Turnip yeah, I wrote it without arguments just as an illustration. But the problem is not even that I need multiple parameters, is that the function won't even be called, since the link won't have a `runat="server"` on it – Pretzel May 25 '20 at 15:17
  • 1
    You need to call your server side function manually from the codebehind. Pass parameters along with __doPostback() that will allow you to identify the event. Inspect the parameters in PageLoad and call your function. Here is a simple example: https://stackoverflow.com/questions/3591634/how-to-use-dopostback – Turnip May 25 '20 at 15:32
  • @Turnip It worked! The redirection from the PageLoad was a good idea. Thanks a lot (: – Pretzel May 25 '20 at 21:20

1 Answers1

0

You can do it by using ASP,NET Ajax PageMethods

Refer this

https://www.c-sharpcorner.com/UploadFile/amit12345/call-pagemethod-from-jquery-ajax/

If you are fine to use ajax script manager control , then this can be approach.

https://www.aspsnippets.com/Articles/Calling-ASPNet-AJAX-PageMethods-using-ScriptManager-Example.aspx

Call it from doStuff() in your case here...

Ajay Kelkar
  • 4,591
  • 4
  • 30
  • 29
  • Good solution, although in this case we are limited to static methods, right? – Pretzel May 27 '20 at 14:13
  • Yes static methods. If you need to maintain some state you can use Cache or Session in page methods.... HttpContext.Current.Session or System.Web.HttpContext.Current.Cache – Ajay Kelkar May 29 '20 at 14:27