最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Access C# Variable From JavaScript - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Feb 26, 2012 at 23:55 John DoeJohn Doe 1491 gold badge4 silver badges10 bronze badges 1
  • Look at the generated source code and you will be enlightened (I hope) – SLaks Commented Feb 26, 2012 at 23:57
Add a comment  | 

6 Answers 6

Reset to default 8

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.

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.

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);

It will work

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

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.

For Razor following works.

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

发布评论

评论列表(0)

  1. 暂无评论