1

I have a Html Helper method that checks if a Section is defined and if not it should write out a partial file.

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?).

Although I dont know how I could pass the @Html.RenderPartial(..) method as a parameter in the following function? 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"))

1 Answer 1

1

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:

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.