简体   繁体   中英

Pass data from controller to javascript (bypassing the view)

Is it a bad practice to pass data from the controller to the script? , ie:

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

By "bypassing the view" I mean doing it this way:

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

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

The way you are doing it is a bad practice. The correct way is to JSON encode it to ensure that all values are properly encoded from the server to client side javascript:

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

Now whether this is fine compared to generating the markup directly will depend on the exact scenario. But if you intend to loop through this javascript array and spit HTML into the DOM, honestly, I don't quite see the point. Go ahead and directly generate this markup at the server (your second approach).

Final remark about ViewBag : don't use it. Use strongly typed view models instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM