如何基于登录用户 Asp.net mvc 隐藏/显示菜单项

caz*_*ise 3 asp.net asp.net-mvc asp.net-mvc-4

我正在开发一个 ASP.Net MVC 4 应用程序。_Layout 主视图包含一个菜单,我想根据您是否以用户身份登录来隐藏菜单中的某些项目,如果您以管理员身份登录,则显示。

我尝试过的方法确实在客户端的菜单中隐藏了链接选项卡,但是当我以管理员身份登录时,它也会在我希望管理员查看它时隐藏相同的链接选项卡。

只是提一下我没有任何角色或管理员控制器登录基于用户

将不胜感激提前感谢一些帮助。

<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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

Gha*_*ngh 8

在你的布局页面试试这个

@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
}
Run Code Online (Sandbox Code Playgroud)

在您的控制器中添加这些行

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

最后在你的 Web.config 中添加这些行到 System.Web

<authentication mode="Forms">
  <forms loginUrl="Path of your Login view" timeout="2880"></forms>
</authentication>
Run Code Online (Sandbox Code Playgroud)

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