0

I'm used to create custom attributes to prevent different access level to reach some methods in a controller:

[AuthorizeUser(AccessLevel = "Administrator")]
public ActionResult Index()
{
    return View("Index");
}

But now I would like to use the same custom attribute in a view. The goal would be to display some HTML when you are an administrator for example.

It sounds strange but I found nothing about that. Any help would be appreciated.

Léo Davesne
  • 2,103
  • 1
  • 21
  • 24
  • 3
    Is accesslevel essentially role in membership? If so, use Role instead rather than AccessLevel. We're not supposed to reinvent the wheel. And if you're using Roles, you can use User.IsInRole() – Larry May 27 '14 at 15:30
  • Thank you it works now. I used the Roles and it works perfectly! :) – Léo Davesne May 29 '14 at 17:51

2 Answers2

1

I'm not sure if this is the right way but this could work.

Solution1

You can have a boolean in your model to check if a user is in certain role and then create a view based upon that model For example.

public class MyViewWithCustomAuthentication
{
  ....
  public bool IsAdmin{get;set;}
  ...
}

in your controller you can check if the user is in certain role

public ActionResult Index()
{
    var myView = new MyViewWithCustomAuthentication();
    myview.IsAdmin = false;
    if(User.IsInRole("Admin"))
    {
       myView.IsAdmin = true;
    }

    return View(myView);
}

then in view

@model MyViewWithCustomAuthentication
....
@if(Model.IsAdmin == true)
{
  //show HTML
}
else
{
  //hide HTML
}
....

Here you will have one view but you may have to make a small change in your viewmodel as I mentioned.

Solution 2

Another way could be to check if user is in certain role and create different views for different roles, based upon the requirement. This way you can show the desired HTML but then you'll end up having different views.

public ActionResult Index()
{       
    if(User.IsInRole("Admin"))
    {
       return View("ViewForAdmin")
    }

    return View("ViewForNonAdmin");
}

If anyone has any suggestions feel free to edit or comment.

Cybercop
  • 8,475
  • 21
  • 75
  • 135
0

You should be able to use partial views and RenderAction.

[ChildActionOnly]
[AuthorizeUser(AccessLevel = "Administrator")]
public ActionResult AdminPartial() {
  return PartialView();
}

And inside the view, where you want that admin HTML snippet.

@{Html.RenderAction("AdminPartial");}
dereli
  • 1,814
  • 15
  • 23