Im using asp.net mvc 2.0. I have the following HtmlHelper extension:
AdminOnly(HtmlHelper helper, IPrincipal User, string htmlToRender)
{
//Render Html if have admin access.
}
I need to modify it to use in such a way: AdminOnly(User).TextBoxFor(x=>x.MyField) So that it could render edit field for MyField only if user has admin access.
For now Ive come out with the following solution:
AdminOnly(this MvcHtmlString resString, IPrincipal User)
{
//Render Html if have adm开发者_如何学JAVAin access.
}
So in code I can write things like:
<%:Html.TextBoxFor(x=>x.MyProperty).AdminOnly(User)%>
It works but I would like to be able to add more inputs or more flexibility to add text before and after the inputs, like this:
<%:Html.PlainText("Set your age: ").TextBoxFor(x=>x.Age).AdminOnly(User)%>
or
<%: Html.AdminOnly("Set your age: ", User).AddTextBoxFor(x=>x.Age)%>
1) If you don't expect rendering stuff for other than current identity and you are using Thread.CurrentPrincipal
I'd recommend to leave out the user
parameter and using HttpContext.Current.User
or Thread.CurrentPrincipal
.
2) Using chained method calls would probably require quite a bit of work, instead I recommend taking advantage of lambda expressions.
Extension:
public static MvcHtmlString AdminOnly(this HtmlHelper htmlHelper, Func<MvcHtmlString> action)
{
if (HttpContext.Current.User.IsInRole("admin"))
return action();
return MvcHtmlString.Empty;
}
Usage:
<%: Html.AdminOnly(() => Html.TextBoxFor(m => m.Field)) %>
edit: updated for mvc 2
精彩评论