Javascript, Razor and Escape characters. Like apostrophe

I would write your foreach like this:

            @foreach (var s in ViewBag.Sessions)
            { 
                <text>
                {
                 title: '@HttpUtility.JavaScriptStringEncode(s.Name)',
                 start: new Date(@s.Starts.Year, @s.Starts.Month-1, @s.Starts.Day),
                 end: new Date(@s.Ends.Year, @s.Ends.Month-1, @s.Ends.Day)
                },
                </text>
            }
  • HttpUtility.JavaScriptStringEncode to escape quotes and html markup.
  • <text> is nicer for multiline output.

Leave a Comment