Search code examples
asp.net-mvcasp.net-mvc-4viewbag

ViewBag is not written in output for Razor


ViewBag value is completely ignored while running ASP.NET MVC4 web page.

enter image description here

Here is the source for above image. Even though I am checking if the ViewBag.SearchResultsJson is null or empty, ViewBag still isn't written in the output.

<script>
    @{
        HtmlString jsonText = new HtmlString("");
        if (!string.IsNullOrWhiteSpace(ViewBag.SearchResultsJson))
        {
            jsonText = Html.Raw(ViewBag.SearchResultsJson);
        }
    }

    $(document).ready(function() {
        var json = @jsonText;
        app.value('searchResultsJson', json);
    })
</script>

What am I missing here?


Solution

  • According your code, an empty jsonText is a valid scenario so I won't focus on why this variable is empty.

    The reason for your error is you're not wrapping @jsonText with quotes to render a valid string on Javascript side.

    You should change

    var json = @jsonText;
    

    by

    var json = '@jsonText';