Razor doesn't understand unclosed html tags

asp.net Mvc-3Razor

asp.net Mvc-3 Problem Overview


With RazorViewEngine, I can do this:

if (somecondition) {
     <div> some stuff </div>
}

but I can't seem to do this (Razor gets confused):

if (somecondition) {
    <div>
}

if (someothercondition) {
    </div>
}

I have a situation in which I need to put my opening and closing html tags in different code blocks - how can I do this in Razor?

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

Try like this:

if (somecondition) {
    @:<div>
}

Solution 2 - asp.net Mvc-3

To explain Darin's answer, i.e prefixing the HTML like this:

@:<html>

@: in Razor means 'render something as plain text'

or you can use this, which outputs the HTML as you orginally wrote it (this can also be used to avoid the automatic HTML encoding that Razor does if you're trying to output HTML):

@Html.Raw("<html>")

(Html.Raw reference from MS - http://msdn.microsoft.com/en-us/library/gg568896(v=vs.111).aspx)

Solution 3 - asp.net Mvc-3

You can create a custom MVC Helper method. For with you create a public static class MyRenderHelpers in namespace System.Web.Mvc.Html and write a method Html.

namespace System.Web.Mvc.Html
{
    public static class MyRenderHelpers
    {
        public static MvcHtmlString Html(this HtmlHelper helper, string html, bool condition)
        {
            if (condition)
                return MvcHtmlString.Create(html);
            else
                return MvcHtmlString.Empty;
        }
    }
}

Now you can use this extension method in your razor view:

@Html.Html("<div>", somecondition)

Solution 4 - asp.net Mvc-3

The fact that you have to do this usually indicates that your view code is not factored correctly. The nature of HTML is to have balanced or self-enclosed tags (at least in HTML 4, HTML 5 seems to be leaning away from it) and Razor depends on that assumption. If your going to conditionally ouptut a <div> then you will also somewhere later output </div>. Just put the whoel pair in your if statement:

@if(something) {
    <div>
        Other stuff
    </div>
}

Otherwise you end up with weird code like here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsydneyosView Question on Stackoverflow
Solution 1 - asp.net Mvc-3Darin DimitrovView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3Chris HalcrowView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3Thomas HauserView Answer on Stackoverflow
Solution 4 - asp.net Mvc-3marcindView Answer on Stackoverflow