在主布局页面中包含登录表单 - ASP.NET MVC 3

时间:2013-03-26 21:31:44

标签: asp.net-mvc asp.net-mvc-3

我正在尝试将我的登录表单包含在_Layout.cshtml文件中,但我遇到了一些问题。

首先,当我提供错误的用户名和/或密码,或输入字段未通过验证时,而不是在局部视图中显示错误消息,这会使局部视图占用整个屏幕!

这是局部视图:http://i.imgur.com/oisCj85.png?1

这是登录时出现问题时返回的“部分”视图:http://i.imgur.com/Uc5Sh2t.png?1

其次,当登录 成功时,用户确实登录,页面“重新加载”,但_Layout.cshtml中的<body onload="loadPage();>中的Javascript没有执行(因此我无法让登录栏再次显示,因为默认情况下它已折叠)。 编辑:这个问题现在解决了,JS没有执行,因为它有错误。它引用了一个仅在您未登录时显示的按钮,显然在 登录时会破坏代码:)

这是我的代码:

_LogOn.cshtml:

@model project_blok_c_groep_13_webshop.Models.LogOnModel

@{
    if (Request.IsAuthenticated)
    {
    <div class="minicolumn">
        U bent ingelogd als: @User.Identity.Name
    </div>
    <div class="minicolumn miniborder">
        Click here to log out!
    </div>
    }
    else
    {
    <div class="minicolumn">
        @using (Html.BeginForm("_LogOn", "Account", new { ReturnUrl = Request.QueryString["ReturlUrl"] }))
        {
            <span style="color:red">@Html.ValidationSummary(true, "Incorrecte gebruikersnaam en/of wachtwoord.")</span>
            <fieldset>
                Gebruikersnaam:
                @Html.TextBoxFor(model => model.Username)
                @Html.ValidationMessageFor(model => model.Username)

                Wachtwoord:
                @Html.PasswordFor(model => model.Password)
                @Html.ValidationMessageFor(model => model.Password)

                <input type="submit" value="Log-in" />
            </fieldset>
        }
    </div>
    }
}

_Layout.cshtml:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
 <!-- saved from url=(0014)about:internet -->
 <head>
  <title>Webshop</title>
  <link href="@Url.Content("~/Content/Site.css")" type="text/css" rel="stylesheet" />
  <link href='http://fonts.googleapis.com/css?family=Merriweather+Sans' rel='stylesheet' type='text/css' />

  <script type="text/javascript">
      <!--lots of javascript omitted here-->
  </script>

 </head>

 <body onload="loadPage();">
  <div class="maindiv">
   <div class="topbar">
   </div>
   <div id="minibar">
    @Html.ActionLink("Log uit", "LogOff","Account")
    <a href="/">Home</a>
    <a href="#">Catalogus</a>
    <a href="#">Winkelwagen</a>
    <a href="#">Contact</a>
    <a onclick="displayBar();">Account</a>
    <div id="visbar">
        @Html.Action("_LogOn", "Account")
    </div>
   </div>
   <div class="content">
     <div class="sidebar">
        @Html.Action("_Menu", "Home")
     </div>


     <div class="center">
      <noscript>
       <p>
        For full functionality of this site it is necessary to enable JavaScript.
        Here are the <a href="http://www.enable-javascript.com/" target="_blank">
        instructions how to enable JavaScript in your web browser.</a>
       </p>
      </noscript>

      @RenderBody()

     </div>
    </div>
    <div class="footer">

    </div>
   </div>
 </body>
</html>

最后,AccountController:

    public class AccountController : Controller
    {
        private AuthDBController authDBController = new AuthDBController();

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }    

        /*
         * Voor de expandable bar.
         */
        public PartialViewResult _LogOn()
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult _LogOn(LogOnModel logOnModel, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                bool auth = authDBController.isAuthorized(logOnModel.Username, logOnModel.Password);

                if (auth)
                {
                    FormsAuthentication.SetAuthCookie(logOnModel.Username, false);
                    return Redirect(returnUrl ?? Url.Action("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("loginfout", "Incorrecte gebruikersnaam en/of wachtwoord.");
                }
            }
            return PartialView(logOnModel);
        }

    }

这些问题令我难过,我已经看了很多其他类似的问题,但没有人得到答案。任何帮助将不胜感激。我想我不了解部分观点,重定向和内容是如何工作的。

1 个答案:

答案 0 :(得分:3)

我做了类似的功能。

控制器操作:

[AllowAnonymous]
    [HttpPost]
    public ActionResult LoginJs(LoginModel m, string returnUrl)
    {
        if(ModelState.IsValid)
        {
            if(ValidateUser(m))
            {
                FormsAuthentication.SetAuthCookie(m.Card, false);

                return Json(new { success = true, redirect = Url.IsLocalUrl(returnUrl) ? returnUrl : Url.Action("Summary") });
            }

            ModelState.AddModelError("", _invalidUser);
        }

        return Json(new { errors = GetErrorsFromModelState() });
    }

    private IEnumerable<string> GetErrorsFromModelState()
    {
        return ModelState.SelectMany(x => x.Value.Errors.Select(error => error.ErrorMessage));
    }

我的_Layout.cshtml代码:

@if (Request.IsAuthenticated)
{
   <div class="enter">
      U bent ingelogd als: @User.Identity.Name
      @Html.ActionLink("Log out", "Logoff", "Members", null, new { @class = "exit"     })
   </div>
}
else
{
    Html.RenderAction("LoginJsGet", "Members");
}

PartialView代码:

@model LoginModel

@using(Html.BeginForm("Login", "Members", FormMethod.Post, new { id = "login", @class = "enter_form" }))
 {
     <span style="color:red">@Html.ValidationSummary(true, "Incorrecte gebruikersnaam en/of wachtwoord.")</span>
            <fieldset>
                Gebruikersnaam:
                @Html.TextBoxFor(model => model.Username)
                @Html.ValidationMessageFor(model => model.Username)

                Wachtwoord:
                @Html.PasswordFor(model => model.Password)
                @Html.ValidationMessageFor(model => model.Password)

                <input type="submit" value="Log-in" />
            </fieldset>
}

和JavaScript:

<script>
$(function () {
    $('#login').unbind('submit');

    $('#login')
        .attr('action', '/Members/LoginJs')
        .bind('submit', function () {
            var form = this;
            if ($("#login").valid()) {
                $.post($(form).attr('action'), $(form).serialize(), function (data) {
                    if (data.errors) {
                        makePopup(data.errors, 'error', 'Ошибка входа');
                    } else {
                        document.location = data.redirect;
                    }
                });
            }

            return false;
        });
});