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

c# - Access cs variables inside javascript - Stack Overflow

programmeradmin1浏览0评论

I have a var variable inside @{} in a cshtml page. I want to access this variable inside a javascript. Is it possible?? How can i do this??

@{  
    var array=[""];    
}

I have a var variable inside @{} in a cshtml page. I want to access this variable inside a javascript. Is it possible?? How can i do this??

@{  
    var array=[""];    
}
Share edited Mar 3, 2011 at 9:47 Fredrik Mörk 158k29 gold badges294 silver badges348 bronze badges asked Mar 3, 2011 at 9:45 Umesha GunasingheUmesha Gunasinghe 7793 gold badges13 silver badges29 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 6

You can try the following approach:

@{
    var array = new [] {"foo", "bar"};
}

<script type="text/javascript">
    var array = [@Html.Raw(String.Join(",", array.Select(s => "'" + s + "'")))];

    alert(array[1]);
</script>

It serializes the C# array as a JavaScript one in the format ["foo", "bar"].

This is a perfect example of when you might want to consider using JSON. Assuming you're developing using ASP.NET Web Pages (as opposed to Web Forms / MVC), in your App_Code directory, make a helper file called Javascript.cshtml with the following code:

@using System.Web.Script.Serialization;

@helper ToJson(object obj) {
    var ser = new JavaScriptSerializer();
    @Html.Raw(ser.Serialize(obj))
}

Now, if your main page you can reference the helper like so: @Javascript.ToJson(myObj). So, in your page you might do something like this:

@{
    var myCSharpObj = new { First = "1st", Second = "2nd" };
}
<script language="javascript">
    var myJSObj = @Javascript.ToJson(myCSharpObj);
    alert(myJSObj.Second);
</script>

Since the variable does not actually exist on the browser your javascript is running in you'll have to use some kind of AJAX type of tech.

Plain old ASMX Web services may be your best bet.

Of course, if you just want it's initial value you can set it as a literal during the position of the page.

I don't have experience with the exact formatting though.

发布评论

评论列表(0)

  1. 暂无评论