chstml:
1 <script type="text/javascript"> 2 $(function () { 3 LoginUserInfo(); 4 }); 5 6 //實現用戶登錄方法 7 function LoginUserInfo() { 8 $("#btnLogin").click(function () { 9 //var postData = { 10 // EmployeeNo: $("#uname").val(), 11 // Pwd: $("#password").val(), 12 // Code: $("#validcode").val() 13 //}; 14 var postData = $("form").serialize(); ///多數據使用自動序列化 輸入表單必須有name性屬 15 alert(postData); 16 //發送異步請求實現登錄 17 $.post("/Login/CheckUserInfo", postData, function (data) { 18 if (data == "Ok") { 19 window.location.href = "/Home/Index"; 20 } else { 21 alert(data); 22 window.location.href = "/Login/Index"; 23 } 24 }); 25 }); 26 } 27 </script> 28 </head> 29 <body> 30 <!---用戶登錄-- 開始-------> 31 <form class="form-horizontal"> 32 <div class="form-group"> 33 <label for="uname" class="col-sm-2 control-label">工號</label> 34 <div class="col-sm-5"> 35 <input type="text" class="form-control" name="EmployeeNo" 36 placeholder="請輸入工號"> 37 </div> 38 </div> 39 <div class="form-group"> 40 <label for="password" class="col-sm-2 control-label">密碼</label> 41 <div class="col-sm-5"> 42 <input type="text" class="form-control" name="Pwd" 43 placeholder="請輸入密碼"> 44 </div> 45 </div> 46 <div class="form-group"> 47 <div class="col-sm-offset-2 col-sm-10"> 48 <button type="submit" class="btn btn-default" id="btnLogin">登錄</button> 49 </div> 50 </div> 51 </form> 52 <!---用戶登錄-- 結束-------------> 53 </body>
后台代码
[HttpPost]
public ActionResult CheckUserInfo(UserInfo userInfo, string validcode)
{
//獲取驗證碼
string sessionCode = Session["ValidateCode"].ToString();
//去掉驗證碼
Session["ValidateCode"] = null;
//判斷驗證碼
if (string.IsNullOrEmpty(sessionCode) || sessionCode != validcode.ToUpper())
{
return Content("驗證碼輸入不正確");
}
string userInfoError = "";
var loginUserInfo = UserInfoService.CheckUserInfo(userInfo);
UserInfoService.GetEntities(u => u.EmployeeNo == userInfo.EmployeeNo && u.Pwd == userInfo.Pwd)
.FirstOrDefault();
if (loginUserInfo!=null)
{
return Content("Ok");
Session["LoginUserInfo"] = loginUserInfo;
}
else
{
return Content("用戶名密碼錯誤");
} return Content(userInfoError);
}
注意的是前台input标签需要name属性与后台代码相对应,使用serialize会自动序列化