Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net MVC3 razor: display actionlink based on user role

I'm new to MVC. I want to be able to hide some actionlinks for some users. Say I have a "create" actionlink which I only want administrators to see and click. I want to use some sort of "loggedintemplate" available in asp.net, but it doesn't seem to work in razor.

I could use some sort of code block with an if statement checking the current user and her role, however that may not be best practice?

my index.cshtml..

// want some adminauth attribute here...
@Html.ActionLink("Create New", "Create")

my controller..

// GET: /Speaker/Create
[Authorize(Roles = "Administrators")]
public ActionResult Create()
{
    return View();
}
like image 889
Mathias Nohall Avatar asked Aug 08 '11 12:08

Mathias Nohall


2 Answers

I have in the past created a helper function to only return output when a criteria is met like this:

public static MvcHtmlString If(this MvcHtmlString value, bool evaluation)
{
     return evaluation ? value : MvcHtmlString.Empty;
}

so you can use this:

@Html.ActionLink("Create New", "Create").If(User.IsInRole("Administrators"))

This way it is legible and short

like image 62
Richard Avatar answered Oct 22 '22 09:10

Richard


If you want a code block, that would do in the view :

@if (Roles.IsUserInRole("Administrators"))
{
  <li>@Html.ActionLink("Create New", "Create")</li>
}
like image 42
Matthieu Avatar answered Oct 22 '22 11:10

Matthieu