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.

1
  • The other Question does not deal with JsonConvert.SerializeObject Commented Jun 5, 2015 at 5:41

1 Answer 1

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>
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.