Sunday, December 12, 2010

Pass and Use variables in ASP.net server to the client HTML or JavaScript code - Multiple ways

Any public variables available during the page load (page_load event) is usable as variables in the HTML code. Below are the multiple ways of using them.

Using ASP.net variables:
public partial class VariableTest : System.Web.UI.Page
{
    public string url = "http://www.google.com";
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
}
HTML Usage:
<a href="<%= url %>">click here</a>
Using Sessions:

These session variables might have loaded at any stage of your application. Even global.asax loading will do. Just make sure that they are available during page load.
protected void Page_Load(object sender, EventArgs e)
    {
        Session["newurl"] = "http://www.google.com";
    }
HTML Usage:
<a href="<%= Session["newURL"] %>">Click here</a>
Using Web.Config:
    Web.config file has the variable value as mentioned below.
<appSettings>
    <add key="newURL" value="http://www.google.com"/>
</appSettings>
HTML Usage:
<a href="<%= ConfigurationManager.AppSettings["newURL"] %>">Click Here</a>
Make sure that the namepsaces are referenced from your page. Otherwise you will have to change like System.Configuration.ConfigurationManager.AppSettings["newURL"]

Using the Variables in JavaScript
     Basically, all the above mentioned usages work like a string replace. So, you can even use it in javascript codes as shown below.
<a href="#" onclick="javascript:alert('<%= urls %>');return false;">Click here</a>
Using these variables in Server controls.
     Controls with server rendering enabled (runat="server") will not work using the methods mentioned above. Use Page.DataBind() to do the trick for you. Make sure that you are using <%# %> in this case

Server Code:
public partial class VariableTest : System.Web.UI.Page
{
    public string newurl = "http://www.google.com";
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.DataBind();
    }
}

Designer Code:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="<%# newurl %>">HyperLink</asp:HyperLink>
OR
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="<%# this.newurl %>">HyperLink</asp:HyperLink>

4 comments:

  1. Thank you so much! I can't find anything documented in any of the textbooks that I have. How did you learn this?

    ReplyDelete
  2. @JGregory78: The info is out there, but spread across various websites and was hard to find when i needed this! I just consolidated the necessary items to one place, for others to use. Glad to know that it was useful for you!

    ReplyDelete
  3. Thx, been checking out dotnet. I'm still not certain I like but it but this helps.

    ReplyDelete