Is it possible or is there a workaround to use Razor syntax within JavaScript that is in a view (cshtml
)?
I am trying to add markers to a Google map...
I just wrote this helper function. Put it in App_Code/JS.cshtml
:
@using System.Web.Script.Serialization
@helper Encode(object obj)
{
@(new HtmlString(new JavaScriptSerializer().Serialize(obj)));
}
Then in your example, you can do something like this:
var title = @JS.Encode(Model.Title);
Notice how I don't put quotes around it. If the title already contains quotes, it won't explode. Seems to handle dictionaries and anonymous objects nicely too!