用于防止元素渲染的 Razor 指令

Razor directive to prevent element rendering

我搜索了一个选项,可以在我的 cshtml 文件中使用 razor 有条件地呈现一些 div 标签,例如 angular 指令 ng-if。 通常我写这样的代码

@if (mycond) {
  <div>blub</div>
}

然后我寻找一种更具可读性的方法,例如

  <div asmarttag:mycond>blub</div>

有什么办法可以实现吗?

不确定它是否正是您想要的...但是自定义 HTMLHelper 怎么样?

namespace System.Web.Mvc
{
    public static class CustomHTMLHelpers
    {
        public static IHtmlString Render(this HtmlHelper helper, bool render, string html)
        {

            if (render)
            {
                return helper.Raw(html);
            }
            else
            {
                return new HtmlString("");
            }

        }

    public static IHtmlString Render(this HtmlHelper helper, bool render, MvcHtmlString html)
    {

        if (render)
        {
            return html;
        }
        else
        {
            return new HtmlString("");
        }

    }

}

那么你可以这样做:

@Html.Render(mycond, "<div>blub</div>")

@Html.Render(true, @Html.ActionLink("Home", "Index", "Home"))

肯定会把它变成一个衬垫给你。