目录
1、创建登录类
2、添加控制器-视图
3、修改View视图
4、添加action登录方法
1、创建登录类
public class LoginModel
{
[Required, StringLength(maximumLength: 20, ErrorMessage = "请输入2-20个字符", MinimumLength = 2)]
public string username { get; set; }
[Required, MinLength(6)]
[DataType(DataType.Password)]
public string password { get; set; }
}
2、添加控制器-视图
方法名右键》添加视图》选择Create模板》选择登录模型类
3、修改View视图
@model XXX.Models.LoginModel
@{
Layout = null;
}<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<title>Login</title>
</head>
<body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@using (Html.BeginForm())
{@Html.AntiForgeryToken()
<div class="container">
<div style="width: 465px; height: 400px; margin: auto; margin-top: 200px; background-color:#b0c4de; padding: 28px; border-radius: 8px; border-color: #b3b0de; border-width: 2px "><h4 style="text-align:center">登录中心</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="row mb-5">
<label class="col-sm-2 col-form-label">用户名:</label>
<div class="col-sm-10">
@Html.EditorFor(model => model.username, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.username, "", new { @class = "text-danger" })
</div>
</div>
<div class="row mb-5">
<label class="col-sm-2 col-form-label">密码:</label>
<div class="col-sm-10">
@Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })
</div>
</div>
<div class="row">
<input style="width: 120px; height: 35px; margin: auto; background-color: #b3b0de; " type="submit" value="登录" class="btn btn-success" />
</div><div class="row">
<a style="text-align:right;" href="/Login/Register">注册用户</a>
</div>
</div>
</div>}
</body>
</html>
4、添加重载方法
[HttpPost]
public ActionResult Login(LoginModel dto)
{
Session["loginuser"] = null;//添加登陆人
Session["loginid"] = 0;//添加登陆人id
try
{
if (ModelState.IsValid)//验证模型类是否验证通过
{
//这里验证用户名密码//成功添加Session
Session["loginuser"] = dto.username;
Session["loginid"] =XX;
return Redirect("/Home/Index");//跳转首页
}
}
catch (Exception ex)
{
return Content(@"<script>alert('登录异常!{0}!');history.go(-1);</script>", ex.Message);
}
return View();
}