Search code examples
c#asp.netxamarin-studio

ASP.NET how does markup access to variables in code-behind?


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?


Solution

  • 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 = "...";