在MVC3里面——程序集 System.Web.Mvc.dll, v4.0.30319有這么一個Ajax.BeginForm異步登錄驗證的類型,我們在下面給出一個例子:
在登錄頁面Logion.cshtml。使用@using (Ajax.BeginForm("Login", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "tips", OnBegin = "return ValidateLog()" })){提交Form內容},HttpMethod="提交方式",OnBegin="return validateLog()"是開始提交前,對Form表單的js驗證。我們直接在javascript里面寫validateLog()的js驗證函數就可以了。OnSuccess = "tips"是Form表單成功提交到這個控制器后,然后再根據頁面上的javascript函數tips(data)和它的返回值data,判斷控制器里面回傳過來的JsonResult值,是"true"還是"flase"。
[HttpPost]
public JsonResult Login(FormCollection collection){
string userName = collection["UserName"];
string passWord = collection["passWord"];
//經過數據庫判斷用戶是否存在
//該用戶有何權限
//用戶和權限保存Session等等處理
JsonResult json = new JsonResult();
json.Data = new Json{result="true"}; //給JsonResult對象賦值,登錄結果是否通過
return json //返回json值
}
1、用戶登錄頁面Logion.cshtml
@{
ViewBag.Title = "登錄";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<link href="/Style/index.css" rel="stylesheet" type="text/css" />
<title>登錄</title>
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/PleatedEffects.js" type="text/javascript"></script>
<script src="/Scripts/RenzoManage.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script type="text/javascript">
//登錄驗證
function ValidateLog() {
if (document.getElementById('userName').value == "" || document.getElementById('userName').value.length == 0) {
alert('用戶名不能為空');
document.getElementById('userName').focus();
return false;
}
if (document.getElementById('passWord').vaule == "" || document.getElementById('passWord').value.length == 0) {
alert('密碼不能為空');
document.getElementById('passWord').focus();
return false;
}
}
//登錄回調函數
function tips(data) {
try {
if (data.result == "false") {
alert("用戶名和密碼錯誤");
}
else {
location.href = '/Home/Index';
}
} catch (e) {
alert('異常錯誤');
}
}
</script>
</head>
<body>
<div id="top">
<div class="topbg">
<div class="main_logo_wrap">
<a href="#" class="logo" target="_blank" title="易樂國際">易樂國際</a></div>
<div class="nav">
<div class="floatright">
<a href="#" class="font01 marginright45 btn_time_a">@(DateTime.Now.GetDateTimeFormats('D')[1].ToString())</a>
</div>
</div>
</div>
</div>
<div id="content" class="c">
<div class="rightcontents">
<div class="righttopbg right_wrap">
<div class="righttopword">
您所在的位置: <a href="#">用戶登錄</a>
</div>
</div>
<div class="righttable">
@using (Ajax.BeginForm("Login", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "tips", OnBegin = "return ValidateLog()" }))
{
<table border="0" cellpadding="0" cellspacing="0" class="chaxunbiaoge search_wh">
<tr>
<td height="55px" width="80px" align="right">
用戶名:
</td>
<td width="175px">
<input type="text" name="userName" id="userName" class=" biaogechaxunkuang" tabindex="1"/>
</td>
<td>
<span class="colore6080d marginleft10">*</span> <span class="spanUserName"></span>
</td>
</tr>
<tr>
<td height="55px" align="right">
密碼:
</td>
<td>
<input type="password" name="passWord" id="passWord" class=" biaogechaxunkuang" tabindex="2"/>
</td>
<td>
<span class="colore6080d marginleft10">*</span><span class="spanPassWord"></span>
</td>
</tr>
<tr>
<td height="55px" align="right">
</td>
<td>
<input name="btnlogin" type="submit" class="marginleft10 btn_dl" value="登錄" tabindex="3" style="margin-top: 14px;" />
</td>
<td>
</td>
</tr>
</table>
}
</div>
</div>
</div>
<div class=" clearfloat">
</div>
<div id="bottom">
<div class="bottomwenzi">
<span class="floatright">后台管理系統</span></div>
</div>
</body>
</html>
2、用戶登錄控制器
///<summary>
///用戶登陸
///</summary>
///<param name="collection"></param>
///<returns></returns>
[HttpPost]
public JsonResult Login(FormCollection collection)
{
string userName = collection["userName"];
string passWord = collection["passWord"];
JsonResult json = new JsonResult();
try
{
Users user = UserManage.GetUser(userName, passWord);
if (user != null)
{
Session["LoginUser"] = user;
Roles role = AuthorityManage.GetRoleById(Convert.ToInt32(user.RoleID));
Session["AllowAuthority"] = role.AllowAuthority;
//Session["AllowMenu"] = role.AllowMenu; //2013116
Session["RolesInfo"] = role;
int i = LogRecordsManage.Insert(new LogRecords() { LogMessage = role.Name + user.Username + "於" + DateTime.Now.ToString() + "登錄", OperateID = user.ID, OperateTime = DateTime.Now, OperateType = 8 });
//json.Data = new { result = "true" };
json.Data = new { result = "false" };
}
else
{
json.Data = new { result = "false" };
}
}
catch (Exception ex)
{
Logs.AppLogs log = new Logs.AppLogs("Casino", "Login", userName, 2, ex.Message);
log.Insert();
CasinoWeb.Helper.LogMessage.SaveError(ex);
}
return json;
}