Search code examples
asp.net-mvcrazor

Razor directive to prevent element rendering


I search for an option to render some div-tags in my cshtml files with razor conditionally like the angular directive ng-if. Normally I write code like

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

And I search for a more readable approach like

  <div asmarttag:mycond>blub</div>

Is there any option to achieve that?


Solution

  • Not sure if it's exactly what you want... but what about a custom 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("");
            }
    
        }
    
    }
    

    Then you could do:

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

    or

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

    Would certinly turn it into a one liner for you.