Search code examples
asp.net-mvcdatatablesauthorizationasp.net-identity

Hide some buttons for non authorized users in jquery datatable


I am using jQuery datatable in my Asp.net MVC project. In any row in datatable I have dropdown-menu for some operations like below:

enter image description here

I want to hide some buttons in this dropdown for non-authorized users.

My js code for add this drop-down menu is:

{
    data: 'UserId',
    name: 'UserId',
    render: function (data) {
        return '<div class="btn-group btn-group-sm operation"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">عملیات <span class="fa fa-caret-down"></span></button> <ul class="dropdown-menu"> <li><a href="/Admin/Customer/Edit/' + data + '"><span class="fa fa-pencil"></span>ویرایش</a></li> <li><a href="/Admin/Gift/Details/' + data + '"><span class="fa fa-gift"></span>امتیاز هدیه</a></li> <li><a href="/Admin/Customer/PointDetails/' + data + '"><span class="fa fa-area-chart"></span>گزارش ریز امتیازات</a></li> <li class="divider"></li><li><a href="javascript:void" id="' + data + '" onclick="deleteRow(' + data + ',\'/Admin/Customer/Delete\'' + ')"><span class="fa fa-trash"></span>حذف</a></li></ul> </div>';

    },
    orderable: false
}

I use Asp.net Identity in this project.

How can I do this?

Thanks in advance


Solution

  • Add classes to each button that correspond to the security roles that are allowed to use them. Start with all buttons hidden, then show the buttons that have the classes that correspond to the role(s) authorized for the current userid.

    Something like this:

    <button class="admin">Admin Stuff</button>
    <button class="admin super">Superuser Stuff</button>    
    <button class="admin super normal">Normal Stuff</button>
    <button class="admin super normal guest">Guest Stuff</button>
    

    And then, when you open the page:

    $(document).ready(function () {
        $('button').hide();
        // find the role of the current user
        $('.' + theRole).show();
    });
    

    This example assumes that the names of the security roles are the same names as the classes you added to the buttons. That's the easiest, because it only requires the one line of code. If you can't do that for some reason, you have to use if else statements to determine which role the user is in, and show whichever class is equivalent to the role.