我正在开发一个 ASP .net MVC 项目,在该项目中我使用了数据注释验证器,但它无法正常工作。我是 MVC 的新手。请帮助我
我的模型
public class Home
{
public int i;
[Required(ErrorMessage="Please enter")]
[StringLength(160)]
public string name;
}
我的 Controller
public ActionResult Index()
{
Home h = new Home();
return View(h);
}
[HttpPost]
public ActionResult Index(Home h)
{
if (ModelState.IsValid)
{
return RedirectToAction("Success");
}
//ModelState.AddModelError("name", "Enter name");
return View(h);
}
我的观点
@using (Html.BeginForm())
{
<label for="name">Name: </label>
@Html.TextBoxFor(m=>m.name)
@Html.ValidationMessageFor(m=>m.name)
<input type="submit" value="Register" />
}
最佳答案
要使 DataAnnotation 起作用,您需要定义属性。所以你需要有 get;设置;
[Required(ErrorMessage="Please enter")]
[StringLength(160)]
public string name { get; set; }
关于c# - 注释验证在 ASP .net MVC 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34588090/