I figured it out. I had to escape double or single quotes.
escape single quotes:
vm.field1('@Html.Raw(Model.field1.Replace("'", "\\\'"))');
or escape double quotes:
vm.field1("@Html.Raw(Model.field1.Replace("\"", "\\\""))")
Update
I found that there is security problem with my original solution.
If the input is A'B'C</SCRIPT>
, it'll break the javascript on the page.
To resolve that, I HTML encode everything except single and double quotes.
vm.field1('Html.Raw(Html.Encode(Model.field1).Replace("'", "\\\'").Replace(""", "\""))');
Update 2
I found the AntiXss library has some tools for this and I found this will be even better.
public static class StringExtensions
{
public static string ToQuotedJsString(this string s)
{
return Micorosoft.Security.Application.Encoder.JavaScriptEncode(s, true);
}
}
then in the View:
vm.field1(@Html.Raw(Model.field1.ToQuotedJsString()));