asp.net - 仅在登录 MVC .net 站点时显示 <li> 项目

标签 asp.net .net asp.net-mvc authentication user-roles

我有一个 MVC 模板和 2 个用户角色,只有具有这些角色的用户才能看到并单击导航栏中的 listItem。但是因为所有角色都可以看到它,所以只要不向未登录的人显示它就足够了。这是我的 cshtml

<div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Roles", "Index", "Roles")</li>
                    <li>@Html.ActionLink("Evaluaties", "About", "Home")</li>
            </ul>
            @Html.Partial("_LoginPartial")
        </div>

所以最后一个 listItem Evaluaties 不应该被没有登录的人看到,或者换句话说,只有两个角色 Student (Leerling) 和 Teacher (Begeleider) 不应该看到。在我的 Controller 中使用了哪些。

public ActionResult About()
    {
        if (User.IsInRole("Begeleider"))
        {
            var client = new WebClient();
            var jsonLeerlingen = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));
            var leerlingen = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Leerling>>(jsonLeerlingen);
            var jsonEvaluaties = client.DownloadString(new Uri("http://localhost:8080/projecten/api/evaluaties"));
            var evaluaties = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Evaluatie>>(jsonEvaluaties);
            ViewBag.Message = leerlingen;
            ViewBag.Evaluaties = evaluaties;

        }
        if (User.IsInRole("Leerling"))
        {
            var email = User.Identity.GetUserName();
            var client = new WebClient();
            var jsonLeerlingen = client.DownloadString(new Uri("http://localhost:8080/projecten/api/leerlingen"));
            var leerlingen = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Leerling>>(jsonLeerlingen);
            var jsonEvaluaties = client.DownloadString(new Uri("http://localhost:8080/projecten/api/evaluaties"));
            var evaluaties = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<Evaluatie>>(jsonEvaluaties);
            ViewBag.Message = leerlingen;
            ViewBag.Evaluaties = evaluaties;

        }
        return View();
    }

我尝试使用 if (User.IsInRole("Begeleider")) 但我不能在 a.cshtml 页面中使用它

最佳答案

如果您查看 _LoginPartial.cshtml 局部 View ,您将看到某些实现方式与您尝试执行的方式完全相同。例如:

@if (Request.IsAuthenticated)
{
    <div>You are logged in</div>
}
else
{   
    <div>You are not logged in</div>
}

关于asp.net - 仅在登录 MVC .net 站点时显示 <li> 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39147286/

相关文章:

asp.net - 将 SQL 数据库导出到 Access - ASP.NET

.net - Fusion Log Viewer 的替代品?

asp.net - IdentityServer3:一些声明没有从身份服务器返回

asp.net - 如何在不往返的情况下更新实体? (EF 4)

c# - 将定义的名称放在 asp.net c# 的 reportviewer PDF 中

asp.net - CSS 文件的 https 请求给出 502 Bad Gateway

c# - 是否有可能有一个取消 token 源,仅取消一些服务员?

c# - 如何检查枚举是否包含数字?

c# - 无法找到自动创建的数据库

asp.net-mvc - asp.net mvc jqgrid 使用网格外的按钮提交网格