0

I have a webform with a button:

<asp:Button ID="btn1" runat="server" text="Click me"
            OnClientClick="printVideos(new Object(),new EventArgs(),url,linkName)"/>

and the OnClientClick event is

<script language= "c#" type="text/C#" runat= "server">
    private void printVideos(Object sender, EventArgs e, string url, string linkName) {

        for (int i = 0; i < 4; i++) {
            Response.Write("<a href='"+url+"'target_blank>'"+linkName+"</a>");
        }
    }
</script>

Where url and linkName are defined in the C# code-behind as private strings within the class.

The button does not work, and there are warnings showing that url and linkName are not used. What should I do to let the markup access to the code-behind variables?

Dylan Czenski
  • 1,305
  • 4
  • 29
  • 49

1 Answers1

0

Your first problem is that you are trying to run server side code on the client - change OnClientClick to OnClick.

Next, you will need to set the protection level of your linkName and url properties so that your ASPX markup can access them. You can set this to either public or protected (source). Finally, remove the extra arguments from the printVideos method - the OnClick handler expects a specific method signature. So, your button markup should look something like:

<asp:Button ID="btn1" runat="server" text="Click me" OnClick="printVideos"/>

And your script...

<script language= "c#" type="text/C#" runat= "server">
    private void printVideos(Object sender, EventArgs e) {
        for (int i = 0; i < 4; i++) {
            Response.Write("<a href='"+url+"'target_blank>'"+linkName+"</a>");
        }
    }
</script>

And in your codebehind for the page, declaring your variables:

protected string url = "...";
protected string linkName = "...";
Community
  • 1
  • 1
AdmiralFailure
  • 146
  • 1
  • 11
  • Thanks. But what if the `OnClick` method expects some parameters from outside of the class? – Dylan Czenski Jan 16 '16 at 19:08
  • @DylanChen The default `OnClick` handlers only take the two parameters above (`Object sender, EventArgs e`). There are other ways to get external information into your handler, but you can't pass it as a standard parameter - without knowing a bit more about what it is you're trying to achieve, I can't recommend one way or another. – AdmiralFailure Jan 16 '16 at 19:31