从javascript中的viewbag属性获取值

时间:2015-12-06 07:58:45

标签: javascript c# model-view-controller viewbag

我需要将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.Sectionnull

时,此解决方案也无效

如何修复脚本问题?

1 个答案:

答案 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>