我有一个 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/