John Doe
John Doe

Reputation: 149

Access C# Variable From JavaScript

I have a public property in my code behind named Tab which I'm trying to access in the pages aspx file with javascript but I'm not sure how to get the right value.

This gives me the value I want

alert('<% Response.Write(this.Tab); %>');

This does not

 var x = <% =this.Tab %>;
 alert(x); 

Any ideas?

Upvotes: 5

Views: 28374

Answers (6)

nPcomp
nPcomp

Reputation: 10003

For Razor following works.

var x = '@yourc#variable';
alert(x);

Upvotes: 0

Deepakmahajan
Deepakmahajan

Reputation: 866

It will work

var x = '<% =this.Tab %>';
 alert(x); 

Upvotes: 1

DotNetUser
DotNetUser

Reputation: 6612

Two methods to do it, one is

    var y = '<%=this.Tab %>';

You can also use JavaScriptSerializer in the code behind and have a method to return value of your variable to javaScript code. This helps if you want to return your private data as well and also you can implement more logic to get the values if you want.

Your code behind-

    protected string GetTabValue()
    {
        // you can do more processing here
        ....
        ....
        // use serializer class which provides serialization and deserialization functionality for AJAX-enabled applications.

        JavaScriptSerializer jSerializer=new JavaScriptSerializer();
        // serialize your object and return a serialized string
        return jSerializer.Serialize(Tab);
    }

Your aspx page

    var x = '<%=GetTabValue()%>';
    // called server side method
    alert(x);

You can also user javascript eval function to deserialize complex data structures.

Upvotes: 0

epascarello
epascarello

Reputation: 207557

If you view the source you are probably seeing

var x = mystring;

I would guess you want the quotes too

var x = "<%= this.Tab %>";

Instead of having code inline, why don't you look at RegisterStartUpScript or RegisterClientScriptBlock.

Upvotes: 8

Pointy
Pointy

Reputation: 414086

What about

var x = "<% =this.Tab %>";

? It depends on what the value is of course, but you have to generate valid JavaScript. Indeed, if it's a string, you'll probably want to do more than just quote it unless you have complete control over its value and you know for sure that the value itself won't contain a quote character.

Upvotes: 2

Tesserex
Tesserex

Reputation: 17314

if this.Tab is a string instead of a number, the JS will break because you didn't put quotes around it in the second example.

var x = '<%= this.Tab %>';
alert(x);

Upvotes: 1

Related Questions