Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling jQuery function using C# CodeBehind with return value

I have an ASP.NET application that will be used to display information from a server regarding various sites for a water company. I have a jQuery method that returns the text of the hyperlink which has been clicked within the div 'info':

<script type="text/javascript">
        $('#info a').click(function getName()
        {
            return ($(this).text());
        });
</script>

I can call this method using C# codebehind using the code

ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "getName()", true);

However I cannot get its return value, which is what I need. Can anyone shed some light on this?

like image 933
Phil Avatar asked Oct 01 '13 08:10

Phil


2 Answers

Use hidden field :

<input type="hidden" id="myhiddenField" name="myhiddenField" runat="server" />

And JQuery (have not tested this) :

<script type="text/javascript">
        $('#info a').click(function getName()
        {
            $("#myhiddenField").val($(this).text());
        });
</script>

And then you would be able to access hidden field in code behind myhiddenField.Value.

Or if you want to use Ajax Call see tutorial here

EDIT :

I created a little project and the below works fine for me (I get alert "testing"):

 <script type="text/javascript">
        $(document).ready(function () {
            $('#info a').click(function getName() {
                // As control having runat="server" their ids get changed
                // selector would be like this 
                $("#<%= myhiddenField.ClientID %>").val($(this).text());
                alert($("#<%= myhiddenField.ClientID %>").val());
            });
        });
</script>

<div id="info">
  <a href="#">testing</a>
</div>
<input type="hidden" id="myhiddenField" name="myhiddenField" runat="server" />
like image 168
Zaki Avatar answered Oct 11 '22 15:10

Zaki


You need to fire a button click event from JavaScript in ASP.NET after the document ready

like this

ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "$(function() {
$( ‘#info a
‘ ).click(); });
", true);

for more details see Click()

like image 20
Sain Pradeep Avatar answered Oct 11 '22 14:10

Sain Pradeep