Burst of Ice Burst of Ice - 3 months ago 11
ASP.NET (C#) Question

Only show an <li> item when logged in on MVC .net site

I have an MVC template and I have 2 user roles, only users with these role can see and click the listItem in the navigationbar. But since all the roles can see it, it's enough to just not show it to non logged in people. This is my 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>


So the last listItem Evaluaties should not be seen by not logged in people or in other word only by the two roles Student (Leerling) and Teacher (Begeleider). Which are used in my 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();
}


i tried with
if (User.IsInRole("Begeleider"))
but I can't use that in a.cshtml page

Answer

If you take a look inside the _LoginPartial.cshtml partial view, you will see something implemented in exactly the same way you are trying to do it. So for example:

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