In MVC how can I use the controller to render a partial view only for approved users?

前端 未结 3 537
再見小時候
再見小時候 2020-12-11 20:59

In MVC 5 I am attempting to use the controller to render a partial view only if the (Windows Authenticated) user belongs to one or more of a list of Active Directory groups.

相关标签:
3条回答
  • 2020-12-11 21:44

    @Html.Partial() returns a partial view without calling a controller method. In order to call your controller method, you need to use

    @Html.Action("MonitorCSU")
    

    or

    @{ Html.RenderAction("MonitorCSU") }
    

    Note this assumes that the MonitorCSU() method is in the same controller as the method that generates the main view (other wise you also need to include a parameter for the controller name)

    Refer documentation

    0 讨论(0)
  • 2020-12-11 21:58

    Thanks to @Stephen Muecke and and a commenter whose entry has mysteriously vanished, I have the missing pieces.

    I was able to test this code with several real users and verified the desired behavior happens consistently.

    Controller Block: Main difference: take out authorization and use an if-then block send one of two partial views.

    [ChildActionOnly]                
        public ActionResult MonitorCSU()
        {         
            if (User.IsInRole("DOMAIN\\GroupA")) 
            {
            return PartialView("MonitorCSU");         
            }
            else 
            {
            return PartialView("Unauthorized");
                // this is an empty page
            }
        }
    

    View Block: The key difference is using HTML.Action

    <div class="rowWithCols3">
    @Html.Action("MonitorCSU")
    

    0 讨论(0)
  • 2020-12-11 22:04

    While you've found a solution, you're going to have other problems with it. I would suggest a different approach, which is to use EditorTemplates and create a separate model for the html you want to render. Then, at runtime you would check whether the user is in the groups you specify, and if they are, you create an instance of the model, and if they are not you leave the model null. In this way, when the view is rendered with EditorFor(), it will ignore and not render the template for users who do not have access.

    0 讨论(0)
提交回复
热议问题