简体   繁体   English

在另一个HTML Helper方法中将HTML Helper方法作为参数传递

[英]Pass Html Helper Method as Parameter in another Html Helper Method

I have a Html Helper method that checks if a Section is defined and if not it should write out a partial file. 我有一个HTML Helper方法,该方法检查是否定义了Section,如果没有定义,则应写出部分文件。

For this method I can pass a long string (the partial is rather big) or maybe I could pass the actual method @Html.RenderPartial(..) which would be much more efficient in my opinion (or is it negligible?). 对于此方法,我可以传递一个长字符串(部分字符串相当大),或者我可以传递实际的方法@Html.RenderPartial(..) ,在我看来这将更加高效(或者可以忽略不计?)。

Although I dont know how I could pass the @Html.RenderPartial(..) method as a parameter in the following function? 虽然我不知道如何在以下函数中将@Html.RenderPartial(..)方法作为参数传递? Should I create a delegate? 我应该创建一个代表吗?

    public static HelperResult RenderSectionEx(this WebPageBase webPage, 
                                                string name, ??? defaultContents)
    {
        if (webPage.IsSectionDefined(name))
            return webPage.RenderSection(name);
        else return defaultContents(null);
    }

Usage: 用法:

@this.RenderSectionEx("MetaTags", Html.Partial("~/Views/Shared/Partials/MetaTags.cshtml"))

What would be nice is to have the ability to pass both strings or a function in this method so I could pass small strings, for eg; 最好是可以通过此方法传递字符串或函数,以便我可以传递小字符串,例如;

@this.RenderSectionEx("Title", @<h1>blah</h1>)

@this.RenderSectionEx("MetaTags", Html.Partial("~/Views/Shared/Partials/MetaTags.cshtml"))

Not sure if this will work (don't have a place to test at the moment) but you could create a delegate which would mean the partial is not called unless absolutely necessary: 不知道这是否行得通(目前尚无测试位置),但是您可以创建一个委托,这意味着除非绝对必要,否则不会调用partial:

public static IHtmlString RenderSectionEx(this WebPageBase webPage, 
                                          string name, 
                                          Func<IHtmlString> defaultContentMethod)
{
    if (webPage.IsSectionDefined(name))
        return webPage.RenderSection(name);

    return defaultContentMethod();
}

Then call it in your views like this: 然后像这样在您的视图中调用它:

@RenderSectionEx("blah", () => Html.Partial("~/Views/Shared/Partials/MetaTags.cshtml"))

And overload it for string instead of delegate: 并将其重载为字符串而不是委托:

public static IHtmlString RenderSectionEx(this WebPageBase webPage, 
                                          string name, 
                                          string defaultContent)
{
    if (webPage.IsSectionDefined(name))
        return webPage.RenderSection(name);

    return defaultContent;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM