3

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=[""];    
}
0

3 Answers 3

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"].

Sign up to request clarification or add additional context in comments.

5 Comments

I am working on the visual Studio 2010 and MVC3 views.It does work but, it underlines the @Html part and says "Conditional compilation is turned off". And I fill the var array in the cshtml using the foreach and the item count can vary from time to time. So when serializing is it possible to run a loop??How can I do it??
The @Html part is a property of HtmlHelper type and should not be a problem. The code I have shown will work with arrays of arbitrary size. What the code does is to quote all strings first and then join them producing another string "'foo','bar','baz'" which is output in the page.
If we have a validationsummery as @Html.ValidationSummary(true, ""); inside @{} tag,is it possible to take the error to a var variable inside the @{} tag as a string and access it from javascript??How can I do this??
I guess this is worth another question :)
What if "foo" or "bar" contains single quotes, or end in a backslash? This is not safe.
3

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>

1 Comment

I just did pretty much the exact same thing, only to realize there's already a built in helper for this! @Json.Encode. It doesn't convert it to "raw" though, so I created another helper, like yours, but inside you can just put @Html.Raw(Json.Encode(obj));.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.