Conditional JavaScript in MVC Razor Statement

I had an odd case where the Model for a MVC Razor page may or may not be null.   If data exists we need to do some extra javascript on the page that doesn’t get run at any other time.   I had problems figuring out how to check for a “null” Model using javascript.   This StackOverflow post had the example that finally showed me a nice elegant way of writing my code.  Here is another SO post with additional information that uses the <text> option.

    var jsonData = null;
    @if(Model != null)
    {
      @:jsonData=@Html.Raw(Json.Encode(Model.ServerDataItemList))
    }

    koVM = new ScheduledEmailVM(jsonData);
    ko.applyBindings(koVM , document.getElementById("ko_div_id"));

Leave a comment