Razor complains when I put a closing div tag in a if clause

浪尽此生 提交于 2020-12-29 05:14:21

问题


I am trying to do this using Razor templating:

@if(isNew)
{
   <div class="new">
}

...


@if(isNew)
{
   </div>
}

The error is:

cannot resolve the symbol 'div'

Razor doesn't like the ending div tag inside the IF clause, how can I get this to work? Is there an escape I have to use?


回答1:


Razor doesn't like it when you split start/end tags up like this as it can't parse the HTML properly, so you have to escape them as plain text:

@if(isNew)
{
   @:<div class="new">
}

...


@if(isNew)
{
   @:</div>
}    

The more conventional approach would be to repeat the markup inside the div (using partials or otherwise) - which approach is more desirable, I would say, is dependent upon the nature of the markup in between the conditional divs:

@if(isNew)
{
    <div class="new">
        <!-- some markup or partial view -->
    </div>
}
else
{
    <!-- some markup or partial view -->
}

I would prefer this approach if either:

  1. The contained markup can be usefully contained in a partial such that it is reusable elsewhere.
  2. The conditional wrapping markup is more than a couple of lines, at which point escaping markup becomes messy.

I should also add the option of using helper methods:

@helper MainMarkup()
{
    <!-- some markup or partial view -->
}

@if(isNew)
{
    <div class="new">
        @MainMarkup()
    </div>
}
else
{
    @MainMarkup()
}

This is useful if you want to use the second option above but avoid repeating markup or nesting too many partials (particularly if this markup is only relevant for this view).



来源:https://stackoverflow.com/questions/20338335/razor-complains-when-i-put-a-closing-div-tag-in-a-if-clause

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