简体   繁体   中英

Calling code behind function on dynamically generated href

I am generating

<a href="...">

dynamically in a code behind. When I click on the link it needs to run a sub from the code behind and also I need to know which link actually triggered that code behind function.

This is my code behind (dynamically generating link) which is then displayed in div. I literally dump this (below code) as a string into a div:

      <a href='#' 
           id='" + i.MemberId.ToString() + "' 
         Text='Click Me' 
onServerClick='Check_Clicked' 
        runat="server">Click Me
     </a>

And this is what I need to call:

Sub Check_Clicked(sender As Object, e As EventArgs)
    Me.div_result.InnerHtml = "TEST"
End Sub

UPDATE:

Okay I added the following to my project:

<script type="text/javascript">
    $(document).ready(function () {
        $('#inboxLink').click(function () {
            $.ajax({
                type: 'POST',
                url: 'inbox.aspx/GetSomething',
                data: '{ test1: "somevalue" }',
                ContentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert("Success");
                },
                error: function (data) {
                    alert("Fail");
                }
            });
        });
    });
</script>

and then

<System.Web.Services.WebMethod()> _
Public Shared Sub GetSomething()
    Me.div_result.InnerHtml = "TEST"
End Sub

but there are more problems In the code behind

'Me' is only valid within an instance method.

so I am not sure the way I am approaching this problem might be wrong?

Generating an element at the client side with runat="server" will not make it a server control. You better implement an AJAX based architecture.

Generate your client side anchor element (I'm using jquery here)

  $('<a />', { text:'Click Me', id:'<whatever you like>', click:function(){ makeCallToServerWithYourData(yourData); } }).appendTo('yourTargetDivSelector'); 

So that's it if you want to call a server method.

If you just want to change the content of a div when you click on the anchor tag, as in your sample code, just replace the click event handler with whatever you want.

Please mark as answer if it helped you.

Thank you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM