Transferring data from the controller to javascript (bypassing the view)

Is it wrong to transfer data from the controller to the script? , i.e.

<script> @foreach (... in ViewBag.X) { $.mynamespace.x[i] = ... } </script> 

Bypassing my view, I mean doing this as follows:

 <ul id="..." style="display:none;"> @foreach (... in ViewBag.X) { <li id="...">...</li> ... } </ul> 

And then in my script using selectors I could populate my $.mynamespace.x .

+4
source share
1 answer

How you do this is bad practice. The correct way is for JSON to encode it to ensure that all values ​​are correctly encoded from the server to javascript on the client side:

 <script type="text/javascript"> $.mynamespace.x = @Html.Raw(Json.Encode(ViewBag.X)); </script> 

Now, whether this will be great compared to creating the markup directly will depend on the exact scenario. But if you intend to iterate over this javascript array and embed HTML in the DOM, to be honest, I don't quite understand. Go ahead and directly generate this markup on the server (your second approach).

A final note on the ViewBag : do not use it. Use strongly typed view models.

+4
source

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


All Articles