Juvaly
Juvaly

Reputation: 271

Data Annotations with Entity Framework+MVC

I have a very basic entity model which I'm trying to add custom validation messages to.

My metadata looks like this:

namespace My.Models {
[MetadataType(typeof(My.Models.ConsumerMetadata))]
public partial class Consumer
{
}

public class ConsumerMetadata
{
    [StringLength(5)]
    [Required(ErrorMessage="First name is an absolute must!")]
    public string FirstName { get; set; }
} }

The problem is that the data annotation I'm adding not being propagated to the view errors - those remain the default errors.

I'm sure its something simple I'm missing here...

Upvotes: 2

Views: 1855

Answers (2)

Robert Koritnik
Robert Koritnik

Reputation: 105081

What does your view look like? You have to make sure your inputs have correct ids

In MVC1 you would have to write

<%= Html.TextBox("data.FirstName") %>
<%= Html.ValidationMessage("data.FirstName") %>

In MVC2 it's even easier, especially if you have a strong type view ViewPage<Consumer>

<%= Html.TextBoxFor(model => model.FirstName) %>
<%= Html.ValidationMessageFor(model => model.FirstName) %>

Your controller action:

public ActionResult AddConsumer(Consumer data)
{
    if (!this.ModelState.IsValid)
    { ... }
    ...
}

In MVC2, validation will happen before your execution enters this action. So you will be able to simply check ModelState.IsValid. But in MVC it's the best way to write a custom action filter that validates your objects. they you would have to decorate your action with that filter attribute and voila. Your objects will get validated and you can act accordingly.

Upvotes: 0

John Farrell
John Farrell

Reputation: 24754

Did you add a Html.ValidationSummary() to your page?

Upvotes: 1

Related Questions