我可以控制用户授权,包括表单、两个文本框和提交按钮。此控件通过 RenderAction 方法包含在母版页中。我有注册页面(通过 RenderBody 方法包含的视图)也有表单。当我从注册表单提交数据时,也会触发登录控件并调用其处理程序(用于处理 POST 数据的控制器方法)。您可以在下面看到用于授权的控制器方法。从其他表单提交数据后,如何防止将 POST 数据发送到登录控件?
[HttpPost]
public RedirectResult LogIn(AuthViewModel authResult)
{
if (ModelState.IsValid)
{
userService.LogInUser(authResult.Login, authResult.Password, Request.UserHostAddress);
}
else
{
TempData["AuthMessage"] = GetValidationMessage();
}
string redirectUrl = "/";
if (Request.UrlReferrer != null)
{
redirectUrl = Request.UrlReferrer.AbsoluteUri.ToString();
}
return Redirect(redirectUrl);
}
[HttpGet]
[ChildActionOnly]
public PartialViewResult LogIn()
{
if (userService.IsUserLoggedIn())
{
User currentUser = userService.GetLoggedInUser();
ViewBag.LoggedInMessage = currentUser.FullName + "(" + currentUser.Login + ")";
}
return PartialView("AuthControl");
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<div>
<div id="header">
<div>
<div>
@{Html.RenderPartial("SearchControl");}
</div>
</div>
</div>
<div id="right_menu">
<div>
@{Html.RenderAction("LogIn", "Navigation");}
</div>
@{Html.RenderAction("Menu", "Navigation");}
<div>
@{Html.RenderAction("Index", "Messages");}
</div>
<div>
@{Html.RenderAction("TagCloud", "Navigation");}
</div>
</div>
<div id="main_content">
@RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>
授权控制:
@model AuthViewModel
<div class="rounded-corners auth-panel">
@if (ViewBag.LoggedInMessage == null)
{
<div class="auth-container">
@using (Html.BeginForm("LogIn", "Navigation"))
{
<div>
<label for="Login">
Login:
</label>
@Html.TextBoxFor(m => m.Login, new { @class="middle-field"})
</div>
<div>
<label for="Password">
Password:
</label>
@Html.PasswordFor(m => m.Password, new { @class="middle-field"})
</div>
<div class="in-center">
<input type="image" src="@Url.Content("~/Content/Images/submit.png")"/>
</div>
}
</div>
<div class="error-msg">
@if (TempData["AuthMessage"] != null)
{
@Html.Raw(TempData["AuthMessage"].ToString())
}
@Html.ValidationSummary()
</div>
<div class="small-nav-message">
<a href="#" class="registration-link">Registration</a>
</div>
}
</div>
注册页面:
RegistrationViewModel
@{
ViewBag.Title = "Registration";
}
@if (TempData["RegistrationFinished"] == null || !(bool)TempData["RegistrationFinished"])
{
<div class="post content-holder">
<div class="fields-holder">
<div >
<div class="error-msg">
@if (TempData["ValidationMessage"] != null)
{
@Html.Raw(TempData["ValidationMessage"].ToString())
}
</div>
@using (Html.BeginForm())
{
<span>
Email:
</span>
<span>
@Html.TextBoxFor(v => v.Email)
</span>
<span>
Password:
</span>
<span>
@Html.PasswordFor(v => v.Password)
</span>
<input type="submit" value="Register"/>
}
</div>
</div>
</div>
}
else
{
<div>
Activation link was sent to your email.
</div>
}