views:

764

answers:

3

I understand that you can use forms authentication to grant/deny access to certain pages based on the criteria of your choosing.

However I wish to go in a little more specific than that and say, have different buttons appear for users based on thier permissions.

I know I could do something like

if(((User)ViewData["CurrentUser"]).IsEmployee).....

But that doesn't seem very elegant and could get messy very quickly.

Are there any guidelines/tools/framework features that could help me out here?

A: 

I had the same issue a while ago for a WPF application. It could work for ASP.NET as well.

For every "button" (UserControl in WPF) you set by attribute the role needed to execute its functionality.

At the begninning of your Action, you create a list of all the "Buttons" that require a special authorization.

Before calling the "return View()" you call a functions that iterate all you special "Buttons" and sets is visibility based on the role of the user.

For WPF that works because you can't call the method by a get/post request... For the web you should make something more sophisticated not just hide/show the button...

I hope this gives you at least a clue... It worked pretty fine for my implementation, but it was just a prototype...But I think I'll use it in future.

PS: Sample code can be found here

Davide Vosti
Hmm maybe, but it's more than just buttons, certain forms and stuff. Thanks anyhow, I'll give your buttons thing a try later and may grant rep accordingly ;)
qui
Yeah but that's the point. I said button because in my exmaple I used a button. The you can add the Attribute to a full "UserControl" and rendering it or not depending on the role... Maybe this doesn't fit well for web...but that's good that you try ;)
Davide Vosti
+2  A: 

Use role-based authentication, then set roles appropriately. Then you can do things like:

if (ViewContext.HttpContext.User.IsInRole("vEmployee") {

The advantage of this is that it's core ASP.NET functionality -- not even MVC-specific -- so it's going to work with every possible membership provider.

Then you can add a view helper overload for whatever control you want to conditionally display:

public static string TextBox(this HtmlHelper helper, 
    string name, string value, string role, object htmlAttributes)
{
   if helper.ViewContext.HttpContext.User.IsInRole(role) {
       return helper.TextBox(name, value, htmlAttributes);
   } 
   else
   {
       return null;
   }
}

...and call it:

<%= Html.TextBox("name", "value", "vEmployee", null) %>
Craig Stuntz
A: 

Don't do it. Use the controller for that kind of logic

Paco
I have view with many fields. Some fields should displayed only with special cases. I have lot of cases. So, should I create as many views as cases??? wow...
dario-g

related questions