Annotation verification does not work in ASP.net MVC

I am working on an ASP.net MVC project in which I use a data annotation validator and it does not work. I am new to MVC. Please help me on this.

My model

 public class Home
    {
        public int i;

        [Required(ErrorMessage="Please enter")]
        [StringLength(160)]
        public string name;
    }

My 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);
    }

My view

@using (Html.BeginForm())
{

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


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


    <input type="submit" value="Register" />
}
+4
source share
1 answer

For DataAnnotation to work, you need to define properties. Therefore you need to haveget; set;

[Required(ErrorMessage="Please enter")]
[StringLength(160)]
public string name { get; set; }
+6
source

Source: https://habr.com/ru/post/1622704/


All Articles