简体   繁体   中英

How can I use C# code in asp.net to pass a parameter to a JavaScript function?

<% string s=LinkButton_ID.Text; %>
<asp:LinkButton ID="LinkButton_ID" runat="server" Text="LinkButton_Text" onclientclick="JscriptFunction(...)">
</asp:LinkButton>

I want to send the "s" as parameter to JscriptFunction. I try JscriptFunction(<% s %>); but doesnt work. Do you have any suggestions? thank you

Try this:

JscriptFunction('<%= s %>');

Don't forget to quote the text value in your JS function call.

EDIT:

I didn't notice that your call to JscriptFunction is inside your server tag. If you don't have access to jQuery, the easiest way to pass the client-side text of the button is probably this:

onclientclick="JscriptFunction(this.innerHTML)"

Here's an example working on jsFiddle.

You can also pass the client-side ID of the control and manipulate the value using JavaScript. Make sure you have ClientIDMode="Predictable" or ClientIDMode="Static" set on the control if you do it this way.

You'll need to declare your code section to be javascript, and then you need to output the asp.net/c# value as a string. The easiest way is something like:

<script type="text/javascript">
    var s = <% Response.write(LinkButton_ID.Text); %>;
    //do your other javascript stuff
</script>

or

<script type="text/javascript">
    var s = <%= LinkButton_ID.Text %>;
    //do your other javascript stuff
</script>

If you needed to do more logic around this, you could also stick a literal control there and output to it in the code-behind:

<script type="text/javascript">
    var s = <asp:literal id="litMyValue" runat="server">;
    //do your other javascript stuff
</script>

Simple way u can pass/ instead you can use it in the function itself

like

<script>
function JscriptFunction()
{
   var s = <%= LinkButton_ID.Text %>;
  // do what you want here.
}
</script>

<asp:LinkButton ID="LinkButton_ID" runat="server" Text="LinkButton_Text" onclientclick="JscriptFunction();"></asp:LinkButton>

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