0

How do I call a C# method in jquery script with passing parameters? I have a jquery accordion with icons implemented dynamically in code behind, once the user clicks the icon it should redirect to a certain page with passing parameter in the url. The data inside the accordion will be populated from the database and what I want to do is for example, when I click on the edit icon, it'd redirect to the editing page with the id of that specific record.

This is how my jQuery accordion looks like:

screenshot

Accordion code:

<div id="accordion">
    <h3>Section 1 <span class="ui-icon ui-icon-lightbulb"></span></h3>
<div>
<p>
Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
</p>
</div>

An example of code when clicking the icon in jquery accordion:

$('span.ui-icon-lightbulb').click(function(e) {
    alert('Lightbulb');
    e.preventDefault();
    e.stopPropagation();
});

It is similar to the following href functionality

<a href='EditRecord.aspx?recordID=" + record.ID + "'>Edit record</a>

but how to do it in jquery by passing the record id from asp.net c# code behind?

EEE
  • 57
  • 2
  • 8
  • I'd recommend switching from postbacks to using jquery AJAX calls to get your content for the accordions. You can then construct the URL as you like. Look into ~$.ajax~ for jQuery. – Jason Oct 24 '14 at 18:45
  • P.S. My knowledge is limited when it comes to Ajax and jquery. – EEE Oct 24 '14 at 18:51

2 Answers2

0

I've had success in the past using C# and static [Web Methods] with jQuery/Ajax. From what I remember the method had to be declared as a public static [WebMethod].

For example:

 [WebMethod]
 public static FooObj GetFooObj ()
 {
     // some code that returns FooObj 
 }

This thread may be of interest.

ASP.NET calling non-static webmethod from JS AJAX

Community
  • 1
  • 1
Michael Hommé
  • 1,696
  • 1
  • 14
  • 18
0

I found another simple way of doing it, thanks anyway guys.

I'd post it just in case anyone needs it so here it is: first of all, I set the ID of the span tag in code behind to the record's ID. Then, I used e.target.id to get the id of the span element which in the previous step I set it to the record's ID. Finally, I used var url = "EditRecord.aspx?recordID=" + e.target.id; $(location).attr('href', url); to redirect to the edit page.

  <script>
            $(function () {
                $("#accordion").accordion();
                $('span.ui-icon-pencil').click(function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    var url = "EditRecord.aspx?recordID=" + e.target.id;
                    $(location).attr('href', url);

                });
            });

   </script>
EEE
  • 57
  • 2
  • 8