Using Razor within JavaScript

后端 未结 12 2532
萌比男神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:58

    You're trying to jam a square peg in a round hole.

    Razor was intended as an HTML-generating template language. You may very well get it to generate JavaScript code, but it wasn't designed for that.

    For instance: What if Model.Title contains an apostrophe? That would break your JavaScript code, and Razor won't escape it correctly by default.

    It would probably be more appropriate to use a String generator in a helper function. There will likely be fewer unintended consequences of that approach.

提交回复
热议问题