Search code examples
javascriptc#model-view-controllerviewbag

get value from viewbag property in javascript


i need to assign value from viewbag property to javascript variable

I have gone through some of the posts and created the code as per that ..

var selectedID = null;
@if (ViewBag.Section != null) {
    <script type="text/javascript">
        selectedID =ViewBag.Section ;
    </script>
}

But the Problem is that it is not accepting the ViewBag Property inside script and displaying syntax error . Most of the posts has this format of solution ,

I have tried solution like :

1.

@{selectedID =ViewBag.Section ;}

2.

@if(ViewBag.DoAboutTab != null)
{
    var doAboutTab ="something";
} else {
    var doAboutTab ="something_else";
}

this solution is not assigning value to variable outside the @{} code I am able to set constant value but not Viewbag Property by this solution

3.selectedID = '@ViewBag.Section' !== @ViewBag.Section;

this solution is also no working when @ViewBag.Section is null

how can I fix the script problem?


Solution

  • <script type="text/javascript">
        var selectedID = @Html.Raw(Json.Encode(ViewBag.Section));
    </script>
    

    If ViewBag.Section is not defined then you will get:

    <script type="text/javascript">
        var selectedID = null;
    </script>
    

    and if for example ViewBag.Section equals to Some nasty escaped " string then you will get a properly encoded value which will not break your javascript:

    <script type="text/javascript">
        var selectedID = "Some nasty escaped \" string";
    </script>