views:

477

answers:

2

Hi,

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...

+1  A: 

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

jfar
Good call. I did not, and putting one show that my metadata is working as expected. The problem, then, is with Html.ValidationMessageFor(model=>model.Property) - those still show up as "The value '' is invalid". This seems to be a known bug: The value '' is invalid
Juvaly
Validation summary is not necessary. Validation messages display errors in place. It depends how you want your errors displayed.
Robert Koritnik
It matters in this case since the inline validation messages have a known bug (see http://forums.asp.net/p/1529205/3699143.aspx) and the validation summary is the only way to show correct messages.
Juvaly
Ok... I've been using EF and MVC2, but haven't had problems, because I'm using custom ViewModels (POCOs) and all data annotations work like a charm. I wouldn't want to mix DAL into my controller logic anyway because I wouldn't be able to unit test my controllers. Mocking EF is not really an option.
Robert Koritnik
A: 

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.

Robert Koritnik
I'm using MVC2. Read comments above to see that 1. I mentioned I'm using the ValidationMessageFor helper and 2. that this is a confirmed bug.
Juvaly
@Juvaly: thank you. I wasn't aware of this issue, because I don't propagate EF classes to views (so they would be validated). I use POCOs instead.
Robert Koritnik