以下是我的代码,我不知道为什么我的验证器不起作用 第一个代码是用户模型,然后第二个是家庭控制器,最后一个是索引操作结果的视图。我是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>
答案 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");
}
它会检查ModelState
是Invalid
是否会重定向到ModelState
的同一视图,其中包含key
和value
所以如果验证了属性失败,其名称将为key
,并且value
key
验证邮件中的邮件将根据其keys(property names)