0

Let's say that I have an MVC view that has one set of features available to non authorized users, and an extended set of features that is available to authorized users. Currently, I have implemented this by marking up my view with

@if(User.IsInRole(...)) {...}

in several places in the view file. This wasn't a big deal when it was just 2 or 3 things that authenticated users could do beyond the non-authenticated functionality, but now I have this all over the place in a "dashboard" type of page. It seems to be getting kind of messy.

Is there a cleaner or more elegant way to implement this? I am using viewmodels. I am wondering if I should use different viewmodels/views based on role, but then using different viewmodels seems like it might be more difficult to maintain. I am not sure what the best practice is for this, and I am open to ideas.

Edit

One example of what I am doing: I have several lists/tables that allows managers to edit the record, so the code adds an extra

<td>

for the manager-allowed actions. Another use case: when the manager is signed in, an employee name is now an actionlink instead of just text.

1
  • perhaps you could construct it with additional partial actions. Commented Jun 18, 2013 at 13:35

2 Answers 2

3

What you could try is encapsulating each portion of the view that will be interchanged based on roles into partial views. This has worked well for me in the past, and is much cleaner when trying to troubleshoot code as opposed to seeing a bunch of @if statements in a single view.

Sign up to request clarification or add additional context in comments.

2 Comments

Good call on partials. I updated my question with examples. Could partials still be used for these? Thank you.
Yes, what you can do in that case is make a partial for the table template. This way in the template, depending on the row, you can add or remove table cells from the template. It will be a little messy in the table header, but much easier to manage. This way you'll just call the partial when rendering the table.
0

Hmmm. I have this idea. You need list of dashboards enumerations where you have a property like RolesAllowedToAccess (string[])

On the view you can foreach by dashboards enumerations where RolesAllowedToAccess contains current user role.

After you can render partials for each of dashboards. Make sence?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.