How to Show or hide controls based on roles - ASP.NET MVC 4 Razor

前端 未结 3 1932
旧巷少年郎
旧巷少年郎 2020-12-29 07:43

I m working on ASP.NET MVC 4 application.I have a dashboard and my users groups will be based on Windows Domain So I am using WIndows Authentication for authenticating users

3条回答
  •  醉话见心
    2020-12-29 07:54

    Typically you would want to keep your views as clean as possible with little to no logic. I would suggest moving your role checking logic into a controller action and rendering a partial view based on the users role.

    You can use ChildActions and the Html.Action extension method to get this wired up.

    From MSDN:

    A child action method renders inline HTML markup for part of a view instead of rendering a whole view. Any method that is marked with ChildActionOnlyAttribute can be called only with the Action or RenderAction HTML extension methods.

    In your project, create a new Controller called Dashboard and added a single Action called BuildTable.

    public class DashboardController : Controller
    {
        [ChildActionOnly]
        public ActionResult BuildTable()
        {
            if (Roles.IsUserInRole("Administrator"))
            {
                return PartialView("_AdminTable");
            }
    
            return PartialView("_SupportTable");
        }
    }
    

    Include the following line in the view where you want the dashboard table to appear.

    @Html.Action("BuildTable", "Dashboard")
    

提交回复
热议问题