0

Recently I have started to work on show/hide, enable/disable controls based on logged in users role and its assigned permissions. While browsing on the net lot of people have provided to create the custom html helper and also the latest introduced tag helpers.

So, my question is can i show/hide, enable/disable controls using TagHelpers ? or do i need to write html helper only.

Right now I have implemented it as follows using the traditional method

@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>

}

As you can see I have checked the required permission in @Html.TextBoxFor, However this logic is not applicable on all types of controls like select, label etc.

So, how can i make a common approach/class to achieve this thing by using tag helper/html helper ?

XamDev
  • 3,377
  • 12
  • 58
  • 97

1 Answers1

1

If you use the built in authorization pieces you can do this using the IAuthorizationService.

First, you'd need to swap out whatever permissions.CheckPermissions() is, and go back to the 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, wrapping the controls you wish to stop rendering with the checks.

Don't forget you need to duplicate the checks in the controller code, because otherwise developer tools in browsers can be used to add the controls back, regardless of what you rendered in the first place.

blowdart
  • 55,577
  • 12
  • 114
  • 149