Skip to content

Instantly share code, notes, and snippets.

@pseudomuto
Created August 25, 2013 17:11
Show Gist options
  • Save pseudomuto/6335058 to your computer and use it in GitHub Desktop.
Save pseudomuto/6335058 to your computer and use it in GitHub Desktop.
Blog Code: MVC Razor Helpers Using Delegates
public static HelperResult RenderIf<TType>(this HtmlHelper html, Func<TType, HelperResult> template, TType item, bool condition)
{
return html.RenderIf(template, new TType[] { item }, condition);
}
public static HelperResult RenderIf<TType>(this HtmlHelper html, Func<TType, HelperResult> template, IEnumerable<TType> items, bool condition)
{
if (condition)
{
return new HelperResult(writer =>
{
foreach (var item in items)
{
template(item).WriteTo(writer);
}
});
}
//return a blank template
return new HelperResult(writer => { });
}
public static class HtmlHelperExtensions
{
}
public static HelperResult RenderIfInRole<TType>(this HtmlHelper html, Func<TType, HelperResult> template, TType item, string role)
{
return html.RenderIf(
template,
item,
html.ViewContext.HttpContext.User.IsInRole(role)
);
}
@Html.RenderIf(@<text>
<strong>@item.Propertu</strong><br />
</text>,
items,
items.Count > 0
)
@Html.RenderIf(@<text>
<p><a href="@Url.Action("logout")">Logout @item.Name</a></p>
</text>,
this.User.Identity,
this.Request.IsAuthenticated
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment