我需要将viewbag属性中的值赋给javascript变量
我已经浏览了一些帖子,并根据这些创建了代码..
var selectedID = null;
@if (ViewBag.Section != null) {
<script type="text/javascript">
selectedID =ViewBag.Section ;
</script>
}
但问题是它不接受脚本中的ViewBag
属性并显示语法错误。大多数帖子都有这种解决方案,
我尝试了类似的解决方案:
1
@{selectedID =ViewBag.Section ;}
2
@if(ViewBag.DoAboutTab != null)
{
var doAboutTab ="something";
} else {
var doAboutTab ="something_else";
}
此解决方案未将值赋给@{}
代码之外的变量
我可以通过此解决方案
Viewbag
属性
3。selectedID = '@ViewBag.Section' !== @ViewBag.Section;
当@ViewBag.Section
为null
如何修复脚本问题?
答案 0 :(得分:4)
<script type="text/javascript">
var selectedID = @Html.Raw(Json.Encode(ViewBag.Section));
</script>
如果未定义ViewBag.Section
,您将获得:
<script type="text/javascript">
var selectedID = null;
</script>
如果例如ViewBag.Section等于Some nasty escaped " string
,那么你将得到一个正确编码的值,它不会破坏你的javascript:
<script type="text/javascript">
var selectedID = "Some nasty escaped \" string";
</script>