Search code examples
c#asp.net-mvcrazorasp.net-mvc-4razor-2

What is the correct razor syntax for nested and mixed code blocks?


I have razor syntax that's nested and mixed in with html and javascript.

It runs fine except when I do a auto code format, the } keeps getting push out of place.

@section js{
    <script type="text/javascript">
        $(document).ready(function () {

            @if (ViewBag.Searched && ViewBag.Found)
            {
                @:$('#found').show(); $('#permit-info').show();

                @if (ViewBag.PendingRequest)
                {
                    @:$('#request-info').hide(); $('#report-info').show();
                }
                else
                {
                    @:$('#request-info').show(); $('#report-info').hide();
                }
            }
            else
            {
                @if (ViewBag.Searched)
                {
                    @:$('#not-found').show();
                            } // <----- PROBLEM. this } doesn't stay at the right place.
            }
        });
    </script>
}

Solution

  • You have an extra @ on this line:

    @if (ViewBag.Searched)
    

    and this line:

    @if (ViewBag.PendingRequest)
    

    Because you're already in razor code (governed by the parent if/else statements).

    Actually, that still kills the format. Although, if you try using <text> tags instead of @: it works. Try this:

    $(document).ready(function () {
    
            @if (ViewBag.Searched && ViewBag.Found)
            {
                <text>$('#found').show(); $('#permit-info').show();</text>
    
                if (ViewBag.PendingRequest)
                {
                    <text>$('#request-info').hide(); $('#report-info').show();</text>
                }
                else
                {
                    <text>$('#request-info').show(); $('#report-info').hide();</text>
                }
            }
            else
            {
                if (ViewBag.Searched)
                {
                    <text>$('#not-found').show();</text>
                }
            }
        });
    

    Take note: Visual Studio always indents razor views poorly :)