注释验证在ASP .net MVC中不起作用

Vis*_*hnu 4 c# asp.net asp.net-mvc asp.net-mvc-4

我正在开发一个ASP .net MVC项目,我正在使用数据注释验证器,但它无法正常工作.我是MVC的新手.请帮我解决这个问题

我的模特

 public class Home
    {
        public int i;

        [Required(ErrorMessage="Please enter")]
        [StringLength(160)]
        public string name;
    }
Run Code Online (Sandbox Code Playgroud)

我的控制器

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);
    }
Run Code Online (Sandbox Code Playgroud)

我的看法

@using (Html.BeginForm())
{

    <label for="name">Name: </label>
    @Html.TextBoxFor(m=>m.name)


    @Html.ValidationMessageFor(m=>m.name)


    <input type="submit" value="Register" />
}
Run Code Online (Sandbox Code Playgroud)

ram*_*ilu 6

要使DataAnnotation工作,您需要定义属性.所以你需要拥有get; set;

[Required(ErrorMessage="Please enter")]
[StringLength(160)]
public string name { get; set; }
Run Code Online (Sandbox Code Playgroud)