Using Razor within JavaScript

后端 未结 12 2322
萌比男神i
萌比男神i 2020-11-22 04:12

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...

12条回答
  •  死守一世寂寞
    2020-11-22 04:59

    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!

提交回复
热议问题