Created
August 25, 2013 17:11
-
-
Save pseudomuto/6335058 to your computer and use it in GitHub Desktop.
Blog Code: MVC Razor Helpers Using Delegates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 => { }); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class HtmlHelperExtensions | |
{ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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