Search code examples
asp.net-mvcrazordatatablesuser-roles

MVC 5 & Jquery DataTables Column display based on user Role


Using Jquery Datatables in an MVC 5 project. Also using Datatables.MVC5 helper which is making the whole task easier and followed this tutorial to help set it all up for MVC Server Side processing.

I am trying to display button columns i.e. Edit | Delete | as the first two columns based on User Role. These buttons would call my normal MVC Controller.

I can create the buttons, I can not work out how to handle the role checking. My previous client side was easy with Razor Syntax, a lot more tricky now using DataTables.

My Current Table.

        $(function () {
        assetListVM = {
            dt: null,
            init: function () {
                dt = $('#assetdatatable').DataTable({
                    "serverSide": true,
                    "processing": true,
                    "DisplayLength": 25,
                    "ajax": {
                        "type": "POST", // Required to change from 'GET' as this produced server error query string length too long.
                        "url": "@Url.Action("Get","Demo")",
                        "data": // Allows us to return extra data object to controller
                            function (d) {
                                d.excelExport = $("#excelExport").val();
                            }
                    },
                    "scrollY": viewheight, // Calculated to help ensure table is fitting max area of screen with out dropping off screen.
                    "colReorder": true,
                    "select": true,
                    "stateSave": true,
                    "dom": 'fBrtip',
                    "lengthMenu": [[25, 50, 100, 200, -1], [25, 50, 100, 200, "All"]],
                    "buttons": [
                        "pageLength",
                        "copy",
                        "excel"
                        ],
                    "columns": [
// HERE I need to check user Role and choose if to display column or not.
// I have tried Razor @if (User.IsInRole("Sausage")) { }
                        {
                            "title": "button column"
                            "data": "AssetID",
                            "className": 'details_button',
                            "render": function (AssetID)
                            {
                                return '<a class="btn-xs btn-primary glyphicon glyphicon-list-alt" href=/Demo/Details/' + AssetID +'></a>';
                                }
                            },
                        { "title": "AssetID", "data": "AssetID" },
                        { "title": "SIM", "data": "SIM" },
                        { "title": "IMEI", "data": "IMEI" },
                        { "title": "Software", "data": "LoggedOnSoftware" },
                        { "title": "Soft No", "data": "LoggedOnSoftwareVerNo" },
                        { "title": "Last Reset", "data": "LastResetType" },
                        {
                            "title": "Last Log", "data": "LastLogOnTime",
                            "render": function (LastLogOnTime) {
                                return (moment(LastLogOnTime).isValid()) ? moment(LastLogOnTime).format("DD MMM YY") : "-";
                            }
                        }
                    ],
                    "order": [[2, 'asc']]
                });
            }
        }

        // initialize the datatables
        assetListVM.init();
    });

In the column titled buttons column I have tried Razor syntax but not working unlike my previous tables for dummys projects which were all html based. I could send a viewbag object with current user role to view and then check against that, I just do not know how to perform if/else decissions within the table setup.

If anybody has any examples of something like this I could get to grips with or can point me in the right direction it would be greatly appreciated.

I have searched and checked the closest question I found was this old one.

Update: Thanks to Jamie

here is my new working code, which based on current users role will hide the first column.

var RoleCheck = @(User.IsInRole("sausage") ? "true" : "false"); // new check for user role outside of Jquery DataTable function which will work.
            $(function () {
        assetListVM = {
            dt: null,
            init: function () {
                dt = $('#assetdatatable').DataTable({
                    "serverSide": true,
                    "processing": true,
                    "ajax": {
                        "type": "POST", // Required to change from 'GET' as this produced server error query string length too long.
                        "url": "@Url.Action("Get","Demo")",
                        "data": // Allows us to return extra data object to controller
                            function (d) {
                                d.excelExport = $("#excelExport").val();
                            }
                    },
                    "columnDefs": [
                        {
                        "target": [0],
                        "visible": RoleCheck // new variable true or false based on user role.
                        }
                    ]
                    "columns": [
                        {
                            "title": "button column"
                            "data": "AssetID",
                            "className": 'details_button',
                            "render": function (AssetID)
                            {
                                return '<a class="btn-xs btn-primary glyphicon glyphicon-list-alt" href=/Demo/Details/' + AssetID +'></a>';
                                }
                            },
                        { "title": "AssetID", "data": "AssetID" },
                        { "title": "SIM", "data": "SIM" },
                        { "title": "IMEI", "data": "IMEI" },
                        { "title": "Software", "data": "LoggedOnSoftware" },
                        { "title": "Soft No", "data": "LoggedOnSoftwareVerNo" },
                        { "title": "Last Reset", "data": "LastResetType" },
                        {
                            "title": "Last Log", "data": "LastLogOnTime",
                            "render": function (LastLogOnTime) {
                                return (moment(LastLogOnTime).isValid()) ? moment(LastLogOnTime).format("DD MMM YY") : "-";
                            }
                        }
                    ],
                    "order": [[2, 'asc']]
                });
            }
        }
        // initialize the datatables
        assetListVM.init();
    });

Solution

  • you might be able to add a columnDef for that column and set the visibility there.

    "columnDefs": [
            {
                "targets": [ 0 ], //first column
                "visible": @(User.IsInRole("Sausage") ? "true" : "false") // had syntactical error extra colon was there before question mark.
            }
        ]
    

    setting variable instead of using inline Razor code.

    var RoleCheck = @(User.IsInRole("Sausage") ? "true" : "false");
    
    
    "columnDefs": [
            {
                "targets": [ 0 ], //first column
                "visible": RoleCheck 
            }
        ]
    

    https://datatables.net/examples/basic_init/hidden_columns.html