使用 MVC 3,您可以为登录按钮设置 onclick 事件,然后将 ajax POST 发送到登录操作。让登录操作返回 JSON 结果并控制从您的 javascript 函数发送用户的位置。
[HttpPost]
public JsonResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
//Do your authentication
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return Json(true);
}
// If we got this far, something failed, redisplay form
return Json(false);
}
在您的视图中添加一个 Id 到您的表单并在按钮上放置一个点击处理程序。
<% using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { Id = "frmLogOn" }))
{ %>
<%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")%>
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName)%>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.UserName)%>
<%: Html.ValidationMessageFor(m => m.UserName)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Password)%>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.Password)%>
<%: Html.ValidationMessageFor(m => m.Password)%>
</div>
<div class="editor-label">
<%: Html.CheckBoxFor(m => m.RememberMe)%>
<%: Html.LabelFor(m => m.RememberMe)%>
</div>
<p>
<input type="submit" value="Log On" onclick="clicked(); return false;" />
</p>
</fieldset>
</div>
<% } %>
<script type="text/javascript">
function clicked() {
var form = $('#frmLogOn');
$.ajax({
type: 'POST',
url: '/Account/LogOn',
data: form.serializeObject(),
success: function (result) {
if (result == true) {
alert("success");
window.top.location = "/Home/Index";
}
else {
alert("failure");
}
},
error: function (data) {
alert("error");
}
});
}
</script>