如何根据已记录的用户ASP.NET MVC隐藏/显示菜单项



我正在处理ASP.NET MVC 4应用程序。_layout Master View包含菜单,我想根据您以用户的身份登录菜单中的某些项目

我尝试过的方法确实隐藏了客户端菜单中的链接选项卡

仅提到我没有任何角色或管理员控制器登录基于用户

感谢您提前的帮助。

<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>

在布局页面

中尝试一下
@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
}

在您的控制器中添加以下行

Public ActionResult Login(UserModel model)
{
    // Check user provided credentials with database and if matches write this
       FormsAuthentication.SetAuthCookie(model.id, false);
       return View();
}

最后在您的web.config中添加这些行。web

<authentication mode="Forms">
  <forms loginUrl="Path of your Login view" timeout="2880"></forms>
</authentication>

请记住,您有2个Web.config文件,必须在较低的Web.config文件中添加这些文件。