用户在部分视图中登录,显示错误
本文关键字:登录 显示 错误 视图 用户 | 更新日期: 2023-09-27 18:13:38
我想建立一个登录表单,在侧边栏中显示在我的网站的每个页面。如果用户输入了不正确的用户/通行证,我希望在此表单上方显示错误信息(页面的其余部分保持原样),如果他成功登录,我希望表单更改为关于用户的信息列表(同样,页面的其余部分与登录之前相同)。我使用MVC 3 web应用程序项目与默认的互联网应用程序模板。我有这个:
_Layout.cshtml
@{
if (User.Identity.IsAuthenticated)
{
Html.RenderAction("ShowUserInfo", "User");
}
else
{
Html.RenderAction("LogIn", "User");
}
}
用户控件
[ChildActionOnly]
public PartialViewResult ShowUserInfo()
{
// populate loggedInInfo from database based on
// User.Identity.Name
return PartialView("_LoggedInInfo", loggedInInfo);
}
private ActionResult RedirectToPrevious(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/''"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("index", "");
}
}
[ChildActionOnly]
public PartialViewResult LogIn()
{
return PartialView("_LogInForm");
}
//
// POST: /User/LogIn
[HttpPost]
public ActionResult LogIn(LogInModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToPrevious(returnUrl);
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
return RedirectToPrevious(returnUrl);
}
_LogInForm
@model MyProject.Models.LogInModel
<h2>Login</h2>
<p>
Please enter your username and password. @Html.ActionLink("Register", "register", "user") if you don't have an account.<br />
@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
</p>
@using (Html.BeginForm("LogIn", "user")) {
html stuff
}
这几乎是预期的工作,除了当我输入错误的用户名/密码时,页面只是重新加载一个空表单,没有显示错误。我也尝试过其他一些事情,但我要么得到关于我如何不能从部分视图发出重定向的错误,要么我得到部分视图(显示错误)显示为整个视图,所以它显示为单个页面,与网站的其余部分分开。如果我正确登录,一切工作正常。
如何使错误正确显示在表单上方?我宁愿不使用任何Ajax或JQuery来做到这一点。
问题似乎是你正在做一个重定向,而不仅仅是返回适当的视图。
添加模型错误后,需要返回视图,而不是执行重定向:
return View("LoginViewNameGoesHere")
所以这里你不想返回部分视图,而是整个视图。
当做RedirectToAction
和Redirect
时,当前请求以http状态码重定向- 3xx结束,这告诉浏览器使另一个请求到指定的url。这意味着,当前请求的所有验证数据都将丢失,并且对登录url发出全新的纯请求。你得到的表格是空的,没有错误。
你应该做的是在当前请求范围内呈现登录视图,而不是通过重定向。重新显示无效视图的通用模式
public ActionResult Login(LogInModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("Home");
}
return View(model); //! no redirection
}