Hide link based on Role

╄→гoц情女王★ 提交于 2019-12-01 00:17:25

问题


Im new to asp.mvc. I'm trying to develop a portal to maintain employee data. In my system only "Manager" has the rigths to create employee. How do I enable the link when manager log in and disable when employee log in. Thanks

My View

@model IEnumerable<SealManagementPortal_3._0.Models.VOC_CUSTODIAN>
@{
    ViewBag.Title = "List of Custodians";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery("#list2").jqGrid({
            url: '@Url.Action("GridData", "Custodian")',
            datatype: 'json',
            mtype: 'GET',
            colNames: ['Agent ID', 'Branch', 'Unique ID', 'Custodian Name', /*'NRIC No', 'E-Mail', 'Contact No', 'Mobile No',*/'Role', 'Details', 'Edit', 'Delete'],
            colModel: [
                { name: 'Agent ID', index: '', width: 10, align: 'left' },
                { name: 'Branch', index: '', width: 10, align: 'left' },
                { name: 'Unique ID', index: '', width: 10, align: 'left' },
                { name: 'Custodian Name', index: '', width: 10, align: 'left' },                
                {name: 'Role', index: '', width: 10, align: 'left' },
                { name: 'Details', index: '', width: 5, align: 'left' },
                { name: 'Edit', index: '', width: 5, align: 'left' },
                { name: 'Delete', index: '', width: 5, align: 'left'}],
            pager: jQuery('#pager2'),
            rowNum: 10,                
            sortname: 'Id',
            sortorder: "desc",
            viewrecords: true,
            autowidth: true,
            caption: 'Custodians List'
        });
    }); 
</script>
@using (Html.BeginForm())
{
    <table id="list2" class="scroll" cellpadding="0" cellspacing="0"></table>

回答1:


You could use roles. The first and most important thing is to decorate the controller action that is supposed to perform the update with the Authorize attribute and specify the correct roles that the user must posses in order to access this controller action:

[HttpPost]
[Authorize(Roles = "Managers")]
public ActionResult Create(Employee emp)
{
    ...
}

Once everything is secure on the server you could do cosmetics in the view and show the link only if the user is in the Managers role:

@if (User.IsInRole("Managers"))
{
    @Html.ActionLink("Create employee", "Create")
}

You may take a look at the following article for more information about forms authentication and roles.



来源:https://stackoverflow.com/questions/11078423/hide-link-based-on-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!