4

I need to pass values from my asp.net code to a javascript code block in the page.

I know at least two ways to do this:

<script runat=server>
int a = 42;
protected override void OnInit(EventArgs e)
{
   lbl.Text = "42";
}
</script>

<script>
   var a = <%= a %>;
   var b = <asp:Literal runat=server id=lbl>/>;
   alert("the meaning of life=" + a + " or " + b);
</script>

But is there a better way in asp.net WebForms to bind the value of a variable in asp.net code to a javascript block? Both of these seem messy because they don't support intellisense.

2
  • 2
    I think var a = <%= a %>; is basically the standard way of doing it. Don't overthink; it's simple, makes sense and is readable. Commented Nov 15, 2011 at 16:34
  • 1
    While its definitely not the cleanest way of doing it, the way you describe in the question is the "standard" way I'd expect to see .NET page variables sent to a JS function. ASP.NET devs who spend any amount of time doing front end stuff will recognize the <% %> tags instantly and know what's going on. Commented Nov 15, 2011 at 16:44

5 Answers 5

2

I ended up doing something which I think it more robust. In master page I added this:

public Dictionary<string, object> JavaScriptVars { get; set; }

Then I append the result of this function to the page:

public string GetJavaScriptVars()
{
    if (JavaScriptVars.Count == 0) return null;
    StringBuilder sb = new StringBuilder();
    sb.Append("<script>");
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    int i = 0;
    foreach (string s in JavaScriptVars.Keys)
    {
        if (i == 0)
            sb.Append("var ");
        sb.Append(s + "=");

        object o = JavaScriptVars[s];
        if (o is System.Collections.Specialized.NameValueCollection)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (string key in ((System.Collections.Specialized.NameValueCollection)o).Keys)
                dict[key] = ((System.Collections.Specialized.NameValueCollection)o)[key];
            o = dict;
        }
        sb.Append(serializer.Serialize(o));
        sb.Append(i == JavaScriptVars.Count - 1 ? ";" : ",");
        i++;
    }
    sb.Append("</script>");
    return sb.ToString();
}

So now I can do this:

JavaScriptVars["Name"] = "John"; //string
JavaScriptVars["Age"] = 32; //int
JavaScriptVars["Hobbies"] = new string[]  { "Sewing", "Hiking" }; //array

and in my final page, I get:

<script>
    var Name='John',Age=32,Hobbies=["Sewing", "Hiking"];
</script>

So now I have a robust way to pass values with types correctly managed to the page without script blocks or labels.

Sign up to request clarification or add additional context in comments.

Comments

1

Typically, the best solution is to store the value in a hidden field on the page:

var el = document.getElementById("<%=HiddenField1.ClientID%>");
if (el){
    var value = el.value;
}

You could also look into using PageMethods too:
http://geekswithblogs.net/WillSmith/archive/2008/12/09/asp.net-pagemethods-to-the-rescue.aspx

1 Comment

I'm not trying to get a label, I'm trying to pass a value that's on the server side to client side javascript. This is slightly better than just saying <%=a%> since it's wrapped in quotas so you won't see invalid js syntax, but it's not better than var a = '<%=42%>';
0

Add a protected property to your code-behind, and access it from javascript:

server:

Protected ReadOnly Property MeaningOfLife() As Int32

    Get

        Return 42

    End Get

End Property

client:

<script>     

    var a = <%= Me.MeaningOfLife %>;     
    var b = <asp:Literal runat=server id=lbl>/>;     
    alert("the meaning of life=" + a + " or " + b);  

</script>

3 Comments

How is that better than just saying var a = <%= some_variable %>; ?
It gets the value from server to client. If some_variable starts off in code-behind, you can't just refer to it unless you make it protected. It's cleaner to expose it through a property.
There are also other factors at play - for example if your script block is in the <head> element and you try and other controls to it, using <%= variable %> won't work.
0

In you example, I'd stick with var a = <%= a %>;

In case the value of a, the .NET value, has some connection with an element on the page, you might put that value in the element itself. For example, if you have a table row on the page that has extra data that javascript will use, but the data in the context of the row.

<tr data-myvalue='<%=a%>'></tr>

Then you can use javascript (maybe jQuery) to extra that data value, rather than putting a bunch of disconnected variables and values in a <script> block

Comments

0

Declare a variable in your code behind file ,, like:

string s;

You can populate this variable any way you want. Now iyou can access this variable in javascript as follow. (if you need to pass a String you have to specify the delimiters " or '):

var a = '<%= a %>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.