Razor 不理解未封闭的 html 标记

使用 RazorViewEngine,我可以这样做:

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

但我似乎不能这样做(雷泽感到困惑) :

if (somecondition) {
<div>
}


if (someothercondition) {
</div>
}

我有一个情况,我需要把我的开始和结束 HTML 标记在不同的代码块-我怎么能这样做在剃刀?

23303 次浏览

Try like this:

if (somecondition) {
@:<div>
}

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.

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)

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)