tags:

views:

525

answers:

3

Hi, I wish to display content depending on the given role(s) of the active user , in the ASP.NET MVC.

Compare the old fashion way, using WebForms:

protected void Page_Load(Object sender, EventArgs e)
{
   if(User.IsInRole("Administrator")) {
       adminLink.Visible = true;
   }
}

Now how would I go on writing that when using the ASP.NET MVC ? From my point of view, it would be wrong to place it directly in the View File, and assigning a variable for every single view won't be pretty either.

+1  A: 

No you would be placing it in the view file, like so actually:

<% If (User.IsInRole("Administrator")) { %>
<div>Admin text</div>
<% } %>
Ropstah
+4  A: 

Create Html helper and check current user roles in its code:

public static class Html
{
    public static string Admin(this HtmlHelper html)
    {
        var user = html.ViewContext.HttpContext.User;

        if (!user.IsInRole("Administrator")) {
            // display nothing
            return String.Empty;

            // or maybe another link ?
        }

        var a = new TagBuilder("a");
        a["href"] = "#";
        a.SetInnerText("Admin");

        var div = new TagBuilder("div") {
            InnerHtml = a.ToString(TagRenderMode.Normal);
        }

        return div.ToString(TagRenderMode.Normal);
    }
}

UPDATED:

Or create wrapper for stock Html helper. Example for ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName):

public static class Html
{
    public static string RoleActionLink(this HtmlHelper html, string role, string linkText, string actionName, string controllerName)
    {
        return html.ViewContext.HttpContext.User.IsInRole(role)
            ? html.ActionLink(linkText, actionName, controllerName)
            : String.Empty;
    }
}
eu-ge-ne
Interesting. Perhaps I could even create a overload for standard html components or similiar.Like: Html.ActionLink(...).RequireRole("Admin")Anything but having if/else statements all over the place would be a better solution.
Claus Jørgensen
I think it is better to create wrappers for existing Html helpers.
eu-ge-ne
A: 
Mickey Mouse