题目
在C#中基于MVC架构写一个通过网页输入账号名密码,访问数据库,如果存在则创建该用户的系统,先完成基本功能,再往上加注册,返回数据库数据,文件处理等内容。
这不是一个成熟项目,而是通过学习不断更新,并记录自己的思路。
环境
Visual studio 2019+SQL Server
开始项目
准备工作
- 创建一个MVC项目
- 建立数据库
use MyLoginSql; create table userTable(id int identity(1,1) primary key,userName nvarchar(20) not null,pwd nvarchar(20) not null); insert userTable values('zhangsan','zhangsan'),('lisi123','lisi123')
第一步,添加Login控制器
新建一对Login方法,一个用于访问页面,一个用于数据交互,使用HttpGet和HttpPost进行修饰,表明每个方法的功能。
第二步 ,添加LoginViewModel
在Models文件夹中新建类,并添加用户名和密码两个属性,并对属性进行限制,再从控制器访问这两个值。
using System.ComponentModel.DataAnnotations;
namespace MyMVCLoginApp.Models
{
public class LoginViewModel
{
[Display(Name="账号名")]
[Required,StringLength(maximumLength:20,ErrorMessage ="请输入6-20个字符",MinimumLength =2)]
public string Name { get; set; }
[Display(Name ="密码")]
[Required,MinLength(6)]
[DataType(DataType.Password)]
public string Pwd { get; set; }
}
}
第三步,新建View页面
在LoginController中的Login方法基于c#create模板创建视图,并在模型类中选择第二步添加的LoginViewModel类,这样就可以使view页面返回的账号名密码传递给model类的属性中。
第四步,编写访问数据库类
using System.Data.SqlClient;
namespace MyMVCLoginApp.Models
{
public class SqlModel
{
private static string connStr = "Data Source=.;Initial Catalog=MyLoginSql;Integrated Security=True";
public string UesrSelect(string name,string pwd)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = $"select * from userTable where userName='{name}' and pwd='{pwd}';";
cmd.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
conn.Close();
return "true";
}
else
{
conn.Close();
return "false";
}
}
}
}
}
该类中包含连接数据库字符串私有属性,以及查询用户的UserSelect方法,该方法包含两个参数,name和pwd,调用该方法传入这两个参数,就可以查询该账号密码在数据库中是否存在。如果存在返回true否则返回false.
第五步,编写控制器程序
using System;
using System.Web.Mvc;
using MyMVCLoginApp.Models;
namespace MyMVCLoginApp.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
//使用同名成对的方法一个用于访问数据一个用于数据交互,使用HttpGet和HttpPost进行限制
[HttpGet]
//创建create模板页,基于LoginViewModel
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
try
{
SqlModel sqlModel = new SqlModel();
string message = sqlModel.UesrSelect(model.Name, model.Pwd);
if (message == "true")
{
return Content("登陆成功");
}
else
{
return Content("登录失败");
}
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
return View();
}
}
}
效果
-
登录界面
-
登录成功页面
-
登录失败
4.账户名密码格式不正确
小结
至此,基本的查询数据库进行登录操作的简单系统搭建完成,下面会对扩展功能进行尝试。