Razor doesn't understand closed html tags

With RazorViewEngine I can do this:

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

but I can't do it (Razor gets confused):

 if (somecondition) { <div> } if (someothercondition) { </div> } 

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

+80
asp.net-mvc-3 razor
Jan 26 '11 at 20:29
source share
4 answers

Try it like this:

 if (somecondition) { @:<div> } 
+135
Jan 26 '11 at 20:35
source share

To explain Darin's answer, i.e. the HTML prefix as follows:

 @:<html> 

@: in Razor means "do something in plain text"

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

 @Html.Raw("<html>") 

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

+43
Oct. 16 '13 at 9:12
source share

The fact that you should do this usually indicates that your view code is not being taken into account correctly. The nature of HTML is to have balanced or self-closing tags (at least in HTML 4, HTML 5 seems to move away from it), and Razor depends on this assumption. If you are going to conditionally disable <div> , then you will also output somewhere later </div> . Just put a whoel pair in your if :

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

Otherwise, you will get a strange code, for example here .

+3
Jan 26 2018-11-21T00:
source share

You can create your own MVC Helper method. To create a public static class MyRenderHelpers in the System.Web.Mvc.Html and write the Html method.

 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:

 @Html.Html("<div>", somecondition) 
+3
Apr 15 2018-12-12T00:
source share



All Articles