1

I want to create a simple HtmlHelper to that I can use like this:

@using(Html.DisplayIf(Object object))
{
...
}

I tried the method suggested here, but unlike the guy who asked that question I would like the content between the brackets not to be rendered at all, not just hidden.

Is there a way to prevent the textwriter from writing the content between the brackets, or some other method that would be appropriate to solve my problem?

Community
  • 1
  • 1
severin
  • 5,203
  • 9
  • 35
  • 48

1 Answers1

0

Edited

You can use the method described here: Capture wrapped content in BeginForm style disposable html helper. I've applied the first method to your example.

public static class HtmlExtensions
{
    public static HelperResult DisplayIf(this HtmlHelper html, Func<object, HelperResult> template, bool show)
    {
        return new HelperResult(writer =>
        {
            if (show)
            {
                template(null).WriteTo(writer);
            }
        });
    }
}

You can call it like this:

@* Will render *@
@Html.DisplayIf(
    @<span>test1</span>, true
)
@* Will not render *@
@Html.DisplayIf(
    @<span>test2</span>, false
)
Community
  • 1
  • 1
Bruno V
  • 1,721
  • 1
  • 14
  • 32
  • Doesn't work for me, the content is still written two the TextWriter – severin Sep 01 '14 at 14:16
  • What does the object parameter contain? And what kind of check has to be performed to output the content? – Bruno V Sep 01 '14 at 14:23
  • What about `DisplayIf(this HtmlHelper htmlHelper, bool show)`? – Leonardo Herrera Sep 01 '14 at 14:38
  • public static IDisposable DisplaySkjermet(this HtmlHelper htmlHelper, bool show) { return new RoleContainer(null); } – severin Sep 01 '14 at 14:50
  • Even this doesn't prevent the content from rendering – severin Sep 01 '14 at 14:51
  • You are right, the content for an IDisposable helper always renders. Here is a similar question: http://stackoverflow.com/questions/10013095/capture-wrapped-content-in-beginform-style-disposable-html-helper I've updated my answer. – Bruno V Sep 01 '14 at 19:28