简体   繁体   English

将数据从控制器传递到javascript(绕过视图)

[英]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. 然后在我的脚本中使用选择器,我可以填充我的$.mynamespace.x数组。

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: 正确的方法是对JSON进行编码以确保从服务器到客户端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. 但是如果你打算循环遍历这个javascript数组并将HTML吐入DOM,说实话,我并不是很清楚。 Go ahead and directly generate this markup at the server (your second approach). 继续直接在服务器上生成此标记(您的第二种方法)。

Final remark about ViewBag : don't use it. 关于ViewBag最后评论:不要使用它。 Use strongly typed view models instead. 请改用强类型视图模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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