Reputation: 1926
I am trying to create navigation menu in my MVC application using Jquery. I am using http://users.tpg.com.au/j_birch/plugins/superfish/ for this.
However I want to display menu items based on user roles i.e. including asp membership authorization logic so that if the user does not have the required role, he does not see certain menu items.
Can anyone suggest how to proceed.
Thanks
Upvotes: 0
Views: 1158
Reputation: 2071
Since superfish only works client side you need to make sure it only has the right html in the first place, which you define server-side.
Your role provider has a IsUserInRole and GetRolesForUser. You could use that to build up the HTML.
For instance:
@if (RoleProvider.IsUserInRole(user.username, "admin")) {
<li>Admin<li>
}
Upvotes: 2
Reputation: 4793
UPDATE: This answer is more appropriate if you're doing a lot of client-side stuff and communicating with the MVC application only for data. If you're rendering every page from the server then use the answer from Steve.
I think you'll need to communicate the user's roles to the client-side using a controller action that returns JsonResult. E.g.
public class SecurityController : Controller
{
public ActionResult Roles()
{
return new JsonResult
{
Data = System.Web.Security.Roles.GetRolesForUser(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
Then use $.ajax
to retrieve the data client-side and in the callback remove nodes from the DOM that don't match your requirements. E.g.
<ul id="menu">
<li data-roles="Administrator">
Secured
</li>
<li>Any</li>
</ul>
<script type="text/javascript">
$.ajax({
url: "security/roles",
success: function(roles) {
$("#menu li[data-roles]").filter(function() {
var requiredRoles = (this.attr("data-roles") || "").split(",");
for (var requiredRole in requiredRoles) {
if (roles.indexOf(requiredRole) >= 0) {
return false;
}
}
return true;
}).remove();
// TODO call your menu plugin here
// $("#menu").superfish();
},
error: function () {
$("#menu li[data-roles]").remove();
}
});
</script>
Cheers, Dean
Upvotes: 2
Reputation: 32768
If you have the users/roles set up in database then you can create tables, one table will contain the menus and the other one will map the menus with the roles.
You may have to create a child action that will query the database get the menu items for a particular role and renders the menu through a partial view. You can even keep the menu items for a user in session and by that way you can avoid hitting the db on each request.
Hiding the menu items partly solves the problem. You have to use the Authorize filter to secure controllers and actions.
Upvotes: 1