Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor @if inside <script> is rejected by VS11

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

Markup highlighting

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

like image 731
James Avatar asked May 05 '12 10:05

James


1 Answers

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);
    }
}
like image 137
Tohid Avatar answered Oct 23 '22 16:10

Tohid