基于角色隐藏链接

11

我是asp.mvc的新手。 我正在尝试开发一个用于维护员工数据的门户网站。 在我的系统中,只有“经理”拥有创建员工的权限。 当经理登录时,如何启用链接,并在员工登录时禁用它。 谢谢。

我的观点

@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个回答

24

你可以使用角色。第一个也是最重要的事情是,在执行更新操作的控制器动作上使用Authorize属性并指定用户必须拥有的正确角色才能访问此控制器动作:

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

一旦服务器上的所有内容都安全了,您可以在视图中进行美化,并仅在用户处于Managers角色时显示该链接:

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

您可以查看下面的文章,以了解有关表单身份验证和角色的更多信息。


有没有办法避免模板中“Managers”的重复?我想在一个地方进行角色管理,而Authorize属性非常适合我。我能否定义一个HtmlHelper来访问属性的内容? - sshine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接