Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Role-Based Content asp.net mvc

Tags:

asp.net-mvc

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.

like image 893
Claus Jørgensen Avatar asked May 30 '09 00:05

Claus Jørgensen


1 Answers

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;
    }
}
like image 56
eu-ge-ne Avatar answered Oct 08 '22 02:10

eu-ge-ne