-2

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?

Inspector Squirrel
  • 2,548
  • 2
  • 27
  • 38
dance2die
  • 35,807
  • 39
  • 131
  • 194

1 Answers1

1

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';
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155