2

I am trying to re-code the following razor syntax to be workable code and am stuck:

    var ServiceIndex = @ViewBag.ServiceID ;
    var ServiceName = @ViewBag.ServiceName ;
    var ServiceNotes = @ViewBag.ServiceNotes ;

My problem is that right now the ViewBag for those 3 arrays is empty and so it pukes on the lone semicolon.

John Schultz
  • 672
  • 1
  • 10
  • 29

1 Answers1

5

You need to translate it into JSON on a server-side.

<script>
    var ServiceNotes = @(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceNotes)));
    var ServiceName = @(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceName)));
    var ServiceIndex = @(Html.Raw(JsonConvert.SerializeObject(ViewBag.ServiceIndex)));
</script>

Then access it directly in JS.

The empty array is correctly processed by JsonConvert, so, if it is empty you will get something like

var ServiceNotes = [];

For the convenience of debugging and avoiding nested function calls you can also split serializing and output.

@{
   string serviceNotesJson = JsonConvert.SerializeObject(ViewBag.ServiceNotes);
   string serviceNameJson = JsonConvert.SerializeObject(ViewBag.ServiceName);
   string serviceIndexJson = JsonConvert.SerializeObject(ViewBag.ServiceIndex);
}

@section scripts 
{
    <script>
        var ServiceNotes = @(Html.Raw(serviceNotesJson));  
        var ServiceName = @(Html.Raw(serviceNameJson));
        var ServiceIndex = @(Html.Raw(serviceIndexJson));
    </script>
}
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101