In MVC, how can I use the controller to partially view only approved users?

In MVC 5, I try to use the controller for partial viewing only if the user (Windows Authenticated) belongs to one or more of the list of Active Directory groups. There are over 30 different groups that I need to consider, so the "hello world" examples do not fit my needs. After playing the scavenger on the Internet, I managed to put it all together. There are no compilation or runtime errors, but the content is displayed to all users, not specific users. Thus, the desired result has not yet been achieved.

While I can achieve the desired result using the if-then logic in the view, it creates a lot of unnecessary duplication and encourages spaghettization. Therefore, I am trying to do this in the controller.

Summary of the desired result:

When a user loads a watch page, a partial view should only be displayed if the authenticated user belongs to one or more of the groups defined in the controller action. If the user is not logged in, then the partial view is not included.

Controller block:

[ChildActionOnly]
    [Authorize(Roles="Domain\\GroupA,Domain\\GroupB")]
    public ActionResult MonitorCSU()
    {   
        return PartialView("MonitorCSU");            
    }

View block:

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

Failed iterations:

  • In the controller block, I tried (unsuccessfully) to use the if-then block, otherwise a different partial view without content.

    [ChildActionOnly]
      public ActionResult MonitorCSU()   {       if (User.IsInRole( "Domain\GroupA" )) {       return PartialView ( "_ MonitorCSU" );       }              {           return PartialView ( "_ Unauthorized" );       }   }

  • Razor HTML.Action, , .

+4
3

@Html.Partial() . ,

@Html.Action("MonitorCSU")

@{ Html.RenderAction("MonitorCSU") }

, , MonitorCSU() , , ( )

+5

, . , EditorTemplates html, . , , , , . , (), , .

+2

Thanks to @Stephen Muecke and the commentator, whose record mysteriously disappeared, I have the missing parts.

I managed to check this code with several real users and make sure that the desired behavior occurs sequentially.

Controller block: The main difference: withdraw authorization and use the 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
        }
    }

Block View: The key difference is the use of HTML.Action

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

+1
source

All Articles