目录
1、添加模型类
public class RegisterModel
{
[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 AV3024ManageML.Models.LoginModel
@{
Layout = null;
}<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<title>Register</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/Login">返回登录</a>
</div>
</div>
</div>}
</body>
</html>
4、添加重载方法
public ActionResult Register()
{
return View();
}
/// <summary>
/// 用户注册
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Register(LoginModel dto)
{
try
{
if (ModelState.IsValid)
{
//验证注册成功后跳转登陆页面return Redirect("/Login/Login");
}
}
catch (Exception ex)
{
return Content(@"<script>alert('注册异常!{0}!');history.go(-1);</script>", ex.Message);
}
return View();
}