I want to create a view that has different displays according to the role the user is in.
Should I create a different view for different roles or should I check the roles on the Veiw page itself rather than in the actions?
How would I check the role on the view page?
Or should i use check the roles on the Veiw page its self rather than on actions, if so can someone plz show me how do check that on view page
You need to do both. Check roles on actions as a security measure and check roles on views to enable/disable specific controls.
Within your view page the long form of checking a role is
HttpContext.Current.User.IsInRole("Administrator")
many developers will create page helper methods so you can end up with something more concise for your application like
public static bool IsAdmin(this ViewUserControl pg)
{
return pg.Page.User.IsInRole("Administrator")
}
then in your view you can just use this.IsAdmin()
To keep your view clutter down look into using partial views
<% if (IsAdmin())
{
Html.RenderPartial("AdminPanel");
}
else
{
Html.RenderPartial("UserPanel");
}
%>
If the display changes based on the role -- and the change is small -- then I would do the check in the view. If certain views are restricted based on the role, then I would do the check in the controller. If the views are completely different (this would be hard to imagine), then separate views per role may be appropriate.
You may want to abstract out certain role-specific view components into partial views to simplify your view logic -- basically you only have to check to include the partial or not based on the role.
Also, other than to check for "IsAuthenticated", I would move the role checking logic to the controller and pass (as data) to the view information on which elements to include/exclude based on role. This keeps the actual business logic from bleeding into your view.
If you are using MVC the whole point of development is to keep the logic out of the view and in the controller. It seems to me like you'd be better off on a WebForms development track than an MVC track.
All that being said, I do an Admin check on a lot of my pages by using a check like this:
<% if ((bool)ViewData["Admin"]) { %>
<!-- Show admin controls here -->
<% } %>
But if you are attempting to build actual logic into the View then you need to figure out what you can push back to the controller to do the work and have the view be as dumb as possible, acting on flags sent to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With