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"))
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.