4

I am working on an ASP .net MVC project in which I am using data annotation validator and it is not working. 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" />
}

1 Answer 1

6

For DataAnnotation to work you need to define properties. So you need to have get; set;

[Required(ErrorMessage="Please enter")]
[StringLength(160)]
public string name { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.