要求字段验证程序在ASP.NET MVC中不起作用

时间:2017-03-22 17:35:18

标签: c# asp.net asp.net-mvc asp.net-mvc-4

以下是我的代码,我不知道为什么我的验证器不起作用 第一个代码是用户模型,然后第二个是家庭控制器,最后一个是索引操作结果的视图。我是MVC.COuld的新手,请你帮帮我。 感谢

    public class User
    {
        [Required(ErrorMessage = "UserName is required")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Password is required")]
        public string Pasword { get; set; }
    }

     public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string uname,string pass)
        {
            if(ModelState.IsValid)
            { 
             User user = new User();
            user.UserName = uname;
            user.Pasword = pass;
            string Username = ConfigurationManager.AppSettings["username"].ToString();
            string passwrd = ConfigurationManager.AppSettings["password"].ToString();
            if (user.UserName !=null && user.Pasword !=null)
             {
                 if(user.UserName==Username && user.Pasword==passwrd)
                {
                    return RedirectToAction("Detail", "Home");
                }                            
             }  
           }
            return View("Index");
        }


<hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-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="form-group">
            @Html.LabelFor(model => model.Pasword, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Pasword, new { htmlAttributes = new { @class = "form-control" } })              
                @Html.ValidationMessageFor(model => model.Pasword, "", new { @class = "text-danger" })
            </div>
        </div>

1 个答案:

答案 0 :(得分:2)

首先,您应该发送model而不是

等个别属性
[HttpPost]
        public ActionResult Index(User user)
        {
            if(!ModelState.IsValid)
            { 
               return View("Index",user);
            }

            // your code here if model is valid
            return View("Index");
        }

它会检查ModelStateInvalid是否会重定向到ModelState的同一视图,其中包含keyvalue所以如果验证了属性失败,其名称将为key,并且value key验证邮件中的邮件将根据其keys(property names)

填充