Access to cs variables inside javascript

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

@{  
    var array=[""];    
}
+3
source share
3 answers

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 JavaScript in the format ["foo", "bar"].

+6
source

This is a great example of when you want to consider using JSON. Assuming you are developing ASP.NET web pages (as opposed to Web Forms / MVC), create a Javascript.cshtml helper file in your App_Code directory with the following code:

@using System.Web.Script.Serialization;

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

, : @Javascript.ToJson(myObj). , - :

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

Since the variable does not actually exist in the browser your javascript is running in, you will have to use some type of AJAX technology.

The usual old ASMX web services might be your best bids.

Of course, if you just want to get the initial value, you can set it as a literal while composing the page.

I have no experience with accurate formatting.

0
source

Source: https://habr.com/ru/post/1795993/


All Articles