上次的Demo,只做了一个查询列表的功能,而且用的是ajax,今天我们来看下原味的mvc的过程,以登录为例,我们依旧是用sqlite数据库
按上次的步骤,我们已经有了一个可以跑的项目,接下来就是添加Login的Action和View以及Modals
STEP 1 : 我们需要数据库支持,添加用户表users,字段如下
添加用户数据:insert into users(account,password,name) values('123','123','白茶程序员')
STEP 2 :添加Modals
namespace MvcDemo.Models { public class User { public int ID { get; set; } public string Name { get; set; } public string Account { get; set; } public string Password { get; set; } } }
STEP 3 : 添加登录显示界面Action到HomeController
public ActionResult Login() { return View(); }
STEP 4 :添加视图,快速的方法是在Action的名字(也就是Login)上右键
在登录界面上完成基本的表单,表单每项的名字对应Modal的名字,指定Action为GoLogin
@{ ViewBag.Title = "Login"; } <h2>Login</h2> <div> <form action="GoLogin"> <div> @Html.TextBox("Account", "", new { placeholder = "请输入用户名" }) </div> <div> @Html.TextBox("Password", "", new { placeholder = "请输入密码" }) </div> <input type="submit" /> </form> </div>
STEP 5 . 在HomeController中添加GoLogin的Action
/// <summary> /// 执行登录操作 /// </summary> /// <param name="user"></param> /// <returns></returns> public ActionResult GoLogin(User user) { User findUser = null; //用参数的方式,可以避免非法字符,以及sql注入的问题,sqlserver 请用@符号 string sql = "select * from users where account =:account "; //使用using方式,如果发生异常,将会执行Displose方法,conn的Dispose方法会关闭连接 using (SQLiteConnection conn = new SQLiteConnection(System.Configuration.ConfigurationManager.ConnectionStrings["sqliteConnection"].ConnectionString)) { conn.Open(); //执行查询 SQLiteCommand cmd = new SQLiteCommand(sql, conn); cmd.Parameters.Add(new SQLiteParameter(":account", user.Account)); SQLiteDataReader dr = cmd.ExecuteReader(); //将查询的数据填充到User实体 if (dr.Read()) { findUser = new User() { Name=dr["name"].ToString(), Account = dr["account"].ToString(), Password = dr["password"].ToString() }; } conn.Close(); } string Msg = null; if (findUser == null) Msg = "账号不存在!"; else if (findUser.Password != user.Password) Msg = "密码错误!"; if(Msg ==null) { Msg = "登录成功,欢迎回来 , " + findUser.Name; return RedirectToAction("Index", new { message = Msg }); } else { return RedirectToAction("Login", new { user = user, message = Msg }); } }
RedirectToAction("Index", new { message = Msg })是登录成功后跳转,并且传递参数 , 失败的话,还是跳转到Login并且传递失败原因和Modal(输入的内容)
登录界面如下:
验证成功后,不成功,会显示失败原因
源代码我放到了github上面: https://github.com/colys/TeaLearning , 可以用git下,或者直接download zip . 强烈推荐git,不会的去学一下,是源代码管理的工具