Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, Razor and Escape characters. Like apostrophe

I am using Razor in my MVC3 project. And also I'm using FullCalendar JQuery plugin. So when I'm trying to fill the array it works good. Except one thing. If s.Name contains apostrophe it renders like' that's not what I want. I tried to use different methods like Encode and Decode and even MvcHtmlString.Create and result is always the same.

Here is the code snippet:

<head>     <script type='text/javascript'>        $(document).ready(function () {                 $('#calendar').fullCalendar({             header: {                 left: '',                 center: 'title',                 right: 'month,agendaWeek,agendaDay'             },             month: 5,             year: 2011,             editable: false,             events: [             @foreach (var s in ViewBag.Sessions)             {                 @:{                 @: title: '@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)                 @:},             }                    ]         });     }); </script> 

like image 970
iLemming Avatar asked Mar 07 '11 22:03

iLemming


People also ask

How do I allow an apostrophe in JavaScript?

Use the Escape Character ( \ ) to Get an Apostrophe in a String in JavaScript.

How do I escape a string in JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.


1 Answers

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.
like image 181
3 revs, 2 users 97% Avatar answered Sep 21 '22 10:09

3 revs, 2 users 97%