sports
sports

Reputation: 8147

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.

Upvotes: 4

Views: 1714

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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.

Upvotes: 4

Related Questions