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=[""];
}
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:
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: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.
You can try the following approach:
It serializes the C# array as a JavaScript one in the format ["foo", "bar"].