Reputation: 77
I'm working on an ASP.Net MVC 4 application. The _Layout master view contains a menu and I want to hide some of the items in the menu based on if you are logged in as a user and make show if you are logged in as an admin.
the approach that i have tried do hide the link tab within the menu for the client but however when i do login as an Admin it also hides the same link tab when i want it the admin to view it.
Just to mention i do not have any role or admin controller the login is based on the users
would appreciate some help thanks in advance.
<nav>
<ul id="menu">
<li>@Html.ActionLink("Rep Home", "Index" , "Audit")</li>
<li>@Html.ActionLink("Log Out", "Login" , "Home")</li>
@if (ViewContext.HttpContext.User.IsInRole("Admin"))
{
<li><a href="http://example/reports/?report=auditDetails" target="_blank">View your report</a></li>
}
</ul>
public class AccountController : Controller
{
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/User/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
Upvotes: 3
Views: 15220
Reputation: 1381
Try this in your Layout page
@if(User.Identity.IsAuthenticated)
{
<li>Link to show only to logged users</li>
if(User.IsInRole("Admin"))
{
<li>Link show only to Admin </li>
}
}
else
{
links that will show to authenticated and unauthenticated users
}
In your Controller add these lines
Public ActionResult Login(UserModel model)
{
// Check user provided credentials with database and if matches write this
FormsAuthentication.SetAuthCookie(model.id, false);
return View();
}
And Finally in your Web.config add these lines inside System.Web
<authentication mode="Forms">
<forms loginUrl="Path of your Login view" timeout="2880"></forms>
</authentication>
Remember you have 2 Web.config
files and you have to add these files inside the lower Web.config
file.
Upvotes: 9