change Layout based on type of User role

放肆的年华 提交于 2019-12-04 09:12:31

You just need to modify the /Views/_ViewStart.cshtml file.

@{
    if (this.User.IsInRole("Admin") || !this.User.Identity.IsAuthenticated) {
        Layout = "~/Views/Shared/_Layout.cshtml";
    } else {
        Layout = "~/Views/Shared/_LayoutUser.cshtml";
    }
}

You didn't mention what should happen if no user is logged in, so I added the check and just sent them to the _Layout.cshtml view. You should change the logic as needed for your application.

luis

You need to first work in global.asax file add the method Application_PostAuthenticateRequest . Then get your roles from database ex:

  roles = spRepository.GetUserRolByUsername(username)
then add this roles to HttpContext ex:

    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
                            new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));

Finally you can access role from your layout page:

     @if (HttpContext.Current.User.IsInRole("Administrator"))
            {
                Html.RenderPartial("AdminMenu");
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!