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=[""];
}
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 composition of the page.
I don't have experience with the exact formatting though.