user1797079
user1797079

Reputation: 247

Annotation Validation not working

Please help me on the following code. The Model class is using System.ComponentModel.DataAnnotation:

namespace Proj.Models
{
    public class Customer
    {
        [Required]
        public string CustomerID{get;set;}

        [Required]
        public string CustomerName{get;set;}
    }
}

I have created a controller using this model, the action method being:

public class Customer:Controller
{
    public ActionResult Details()
    {
        return View();
    }
}

The razor view is Details.cshtml, having following markup and code:

@model Proj.Models.Customer

<form method="post">

@Html.EditorForModel()

<button>Submit!!</button>

</form>

However, when I click submit, no validation errors are seen as expected.

Upvotes: 2

Views: 100

Answers (2)

Display Name
Display Name

Reputation: 4732

You need to create editor template for your model. By default no validation messages will be emitted. Inside your editor template, you will have to use @ValidationMessageFor for your Required fields.

Hope this helps.

Upvotes: 0

Levi Botelho
Levi Botelho

Reputation: 25194

You need to create a method which takes your model as input like this:

[HttpPost]
public ActionResult Index(Customer customer)
{
    return View();
}

The [HttpPost] ensures that the method is only called on POST requests.

Upvotes: 2

Related Questions