Razor @if inside <script> is rejected by VS11

半腔热情 提交于 2019-12-03 18:01:56

问题


Is the following markup incorrect, or is it a bug in the Razor engine in MVC4? Either way, what's the best workaround?

The entire content of View1.cshtml is shown. It compiles fine, but the Intellisense error highlighting is annoying. (Included as an image so you can see how the syntax is rejected by VS11.)

Hote that the @: syntax (instead of <text></text>) isn't accepted either.


回答1:


It's a little tricky to mix JavaScript with Razor. Personally, I find it easier to always separate these two guys by using either Razor @function or Razor custom @helper.

Here's a simple example:

<script type="text/javascript">
    function btn_clicked() {
        @generateMyJavaScript()
    }
</script>

<a href="javascript:void(0)" onclick='btn_clicked()'>Click on me</a>

@functions {
    private MvcHtmlString generateMyJavaScript()
    {
        string jsBuilder = string.Empty;
        if (true)
            jsBuilder = "alert('Hey!');";
        return MvcHtmlString.Create(jsBuilder);
    }
}



回答2:


I noticed strange behavior of the syntax highlighter too. This is not really an answer but:

  • I try staying away from mixing model data into javascript. Although powerfull it is a bit spaghetti-like.
  • Also I try to have as little as possible tags in the html. I use js includes and jQuery $(document).ready(function () ... functions inside those.
  • There you can extract the JSON data from the data attributes and base javascript decisions on those.

(Wanted to write this as a comment but didn't find the way to do that, sorry for the debump)



来源:https://stackoverflow.com/questions/10460928/razor-if-inside-script-is-rejected-by-vs11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!