ActionResult for Layout

时间:2013-12-15 11:26:07

标签: c# asp.net-mvc authentication layout razor

我正在尝试创建一个位于布局本身的登录表单,因此不在任何视图中。问题是我不知道如何为布局编写ActionResult。

如果我把我的代码放进去让我们说ActionResult Index()那么它只适用于Index页面。那么有什么类似ActionResult for Layout本身的吗?

2 个答案:

答案 0 :(得分:1)

我会这样做:

  1. 创建一个登录操作以返回特定的部分。

    public ActionResult Login()
    {
       if (User.Identity.IsAuthenticated)
       {
          return PartialView("_loggedInPartial");
       }
       else
       {
          return PartialView("_notLoggedInPartial");
       }
     }
    
  2. 在layout.cshtml中调用它,如下所示:

    @Url.Action("Login", "Account");
    
  3. <强>更新

    您还可以检索用户并将其返回到_notLoggedInPartial视图以显示一些用户凭据或欢迎消息,如下所示:

      ...
      else
      {
        // User retrieval code from db
        return PartialView("_notLoggedInPartial", model);
      }
      ...
    

答案 1 :(得分:0)

人们通常不喜欢这样做,但仍然是最简单的实现方式

  1. 使用登录字段在布局中创建表单(html / ajax)。
  2. 从那里发布到您的“登录帖子”操作。

    using (Html.BeginForm("Login", "Account")){
       @Html.TextBox("Username")
       @Html.TextBox("Password")
       <input type="submit" value="Login">
    }
    
  3. AccoutController必须包含具有以下结构的动作。

    [HttpPost]
    Public ActionResult Login(string Username, string Password)
    {
      //handle appliaction logic
    }
    
相关问题