Passing strings with Single Qoute from MVC Razor to JavaScript

Razor will HTML encode everything, so to prevent the ' from being encoded to ', you can use

alert('@Html.Raw(ViewBag.str)');

However, now you've got an actual ' in the middle of your string which causes a javascript error. To get around this, you can either wrap the alert string in double quotes (instead of single quotes), or escape the ' character. So, in your controller you would have

ViewBag.str = "Hi, how\\'s it going?";