【问题标题】:Creating a HtmlHelper to display content if certain conditions are fulfilled如果满足某些条件,则创建 HtmlHelper 以显示内容
【发布时间】:2014-09-02 03:31:46
【问题描述】:

我想创建一个简单的 HtmlHelper,我可以像这样使用它:

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

我尝试了here 建议的方法,但与提出该问题的人不同,我希望括号之间的内容根本不呈现,而不仅仅是隐藏。

有没有办法阻止文本编写者在括号之间写内容,或者其他适合解决我的问题的方法?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    已编辑

    您可以使用此处描述的方法:Capture wrapped content in BeginForm style disposable html helper。 我已将第一种方法应用于您的示例。

    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);
                }
            });
        }
    }
    

    你可以这样称呼它:

    @* Will render *@
    @Html.DisplayIf(
        @<span>test1</span>, true
    )
    @* Will not render *@
    @Html.DisplayIf(
        @<span>test2</span>, false
    )
    

    【讨论】:

    • 对我不起作用,内容还是写了两个TextWriter
    • object参数包含什么?并且必须执行什么样的检查才能输出内容?
    • DisplayIf(this HtmlHelper htmlHelper, bool show) 呢?
    • public static IDisposable DisplaySkjermet(this HtmlHelper htmlHelper, bool show) { return new RoleContainer(null); }
    • 即使这样也不会阻止内容呈现
    猜你喜欢
    • 2017-08-30
    • 1970-01-01
    • 2015-04-24
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多