MVC3学习:利用mvc3+ajax实现登录
用到的工具或技術(shù):vs2010,EF code first,JQuery ajax,mvc3。
第一步:準(zhǔn)備數(shù)據(jù)庫。
利用EF code first,先寫實(shí)體類,然后根據(jù)實(shí)體類自動(dòng)創(chuàng)建數(shù)據(jù)庫;或者先創(chuàng)建數(shù)據(jù)庫,再寫實(shí)體類,都可以。如果實(shí)體比較多,可以先創(chuàng)建數(shù)據(jù)庫后,利用POCO工具來自動(dòng)生成實(shí)體類。
我這里只有一個(gè)登錄用戶表,非常簡單,自己手動(dòng)在Model寫實(shí)體類:
namespace ajaxDemo.Models {public class Users{[Key]public int Uid { get; set; }public string UserName { get; set; }public string PassWord { get; set; }} } View Code using System.Data; //需要添加此命名空間 using System.Data.Entity; //需要添加此命名空間namespace ajaxDemo.Models {public class LoginContext:DbContext{public LoginContext(): base("name=login") //自定義數(shù)據(jù)庫連接字符串 {}public DbSet<Users> Users { get; set; }} }?
第二步:寫控制器
直接上代碼
namespace ajax.Controllers {public class LoginController : Controller{private LoginContext db = new LoginContext();public ActionResult login(){return View();}public ActionResult LogOn(string usn, string pwd){if (Request.IsAjaxRequest()){int n = (from c in db.Userswhere c.UserName == usn&& c.PassWord == pwdselect c).Count();if (n != 1)return Content("-1");elsereturn Content(n.ToString());}return View();}} }login方法是用來生成視圖,LogOn方法用來判斷登錄是否成功。注意:要用Request.IsAjaxRequest()來判斷數(shù)據(jù)的傳送方式,是否是利用ajax來傳送數(shù)據(jù)。
第三步:創(chuàng)建視圖
<h2>用戶登錄</h2> <script type="text/javascript">$(function () {$("#login").click(function () {var username = $("#txtName").val();var password = $("#txtPwd").val();if (username == ""){ alert("用戶名不能為空"); $("#txtName").focus(); return false; }else if (password == ""){ alert("密碼不能為空"); $("#txtPwd").focus(); return false; }else {$.post("LogOn", { usn: username, pwd: password },function (data) {if (data == "-1") alert("用戶名或密碼錯(cuò)誤");else window.location.href = "/Home/Index";});return false;}});}); </script> <fieldset> <legend>登錄框</legend> @using (Html.BeginForm()) {<label>賬號:</label>@Html.TextBox("txtName")<br /><label>密碼:</label>@Html.Password("txtPwd")<br /> <input type="submit" id="login" value="登錄" />} </fieldset>利用JQuery獲取登錄用戶名和密碼,然后POST給LogOn方法,注意:這里傳遞過去的參數(shù)名必須為usn和pwd,要和LogOn方法里面的參數(shù)名一致。
轉(zhuǎn)載于:https://www.cnblogs.com/denny402/p/3162282.html
總結(jié)
以上是生活随笔為你收集整理的MVC3学习:利用mvc3+ajax实现登录的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Repository 仓储,你的归宿究竟
- 下一篇: CSS元素选择器