C#MVC项目---登录

C#MVC项目---登录_第1张图片

目录

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模板》选择登录模型类

 C#MVC项目---登录_第2张图片

3、修改View视图

@model XXX.Models.LoginModel
@{
    Layout = null;
}



   

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    Login


    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @using (Html.BeginForm())
    {@Html.AntiForgeryToken()
   


       

           

登录中心


           

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
           

               
               

                    @Html.EditorFor(model => model.username, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.username, "", new { @class = "text-danger" })
               

           

           

               
               

                    @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })
               

           

           

               
           

           


                注册用户
           

       

   
}

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(@"", ex.Message);
            }
            return View();
        } 

你可能感兴趣的:(C#,c#,mvc,前端)