在 .net 核心中启用禁用控件

Enable disable controls in .net core

最近我开始研究 show/hide、enable/disable 基于登录用户角色及其分配权限的控件。在网上浏览时,很多人提供了创建自定义 html 帮助器以及最新引入的标签帮助器的方法。

所以,我的问题是我可以 show/hide、enable/disable 使用 TagHelpers 进行控制吗?还是我只需要写 html 助手。

目前我使用传统方法实现如下

@if (!permissions.CheckPermission("course.coursedetails.mytextbox.visible"))
{
  <section class="col col-5">
  <label class="label">@objLocalizer["Title"]</label>

  <label class="input">
  <i class="icon-append fa fa-tag"></i>
  @Html.TextBoxFor(model => model.CourseLang.CourseTitle, permissions.CheckPermission  ("course.coursedetails.mytextbox.enabled") ? (object)new { @disabled = "disabled", @class = "form-control", @id =   "mytextbox" } : new { @class = "form-control", @id = "mytextbox" })

  <span asp-validation-for="CourseLang.CourseTitle"  class="text-danger"></span>
  </label>
  </section>

}

如您所见,我已经在 @Html.TextBoxFor 中检查了所需的权限, 但是,此逻辑不适用于所有类型的控件,例如 select, label

那么,我怎样才能通过使用标记 helper/html 帮助器来创建一个通用的 approach/class 来实现这个目标?

如果您使用内置的授权片段,您可以使用 IAuthorizationService 执行此操作。

首先,您需要换出任何 permissions.CheckPermissions(),然后返回 claims based authorization built into asp.net core. Assuming you need something more than a simple claims check then you'd use code policies and requirements to express your rules, then finally you check those policies inside your views,用检查包装您希望停止呈现的控件。

不要忘记您需要在控制器代码中重复检查,否则可以使用浏览器中的开发人员工具将控件添加回去,而不管您首先呈现的是什么。