views:

391

answers:

3

I have an update controller action that checks validation.

if (!ModelState.IsValid) return View(InitialiseModel(model));

My view uses UIHelpers:

<%=Html.EditorForModel("MyModelTemplate") %>

I have a String property in my model called "Title" which has the attribute [Required]:

 [Required]
 [DisplayName("Resource title")]
 public string Title { get; set; }

The UI template for this property looks like this:

<%= ViewData.ModelMetadata.IsRequired ? "*" : "" %>
<label for="<%=ViewData.ModelMetadata.PropertyName %>">
    <%=ViewData.ModelMetadata.GetDisplayName() %>
</label>
<input type="text" id="<%=ViewData.ModelMetadata.PropertyName%>" 
 name="<%=ViewData.ModelMetadata.PropertyName%>" value="<%=Model%>" />

<%= Html.ValidationMessage(ViewData.ModelMetadata.PropertyName, "*") %>

The problem is ViewData.ModelMetadata.IsRequired is always false. And the validation message is never displayed. What am I missing?

A: 

Possibly a bug?

From: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html

Brad Wilson said in reply to Andrew...

I don't believe that [Required] sets IsRequired to be true today, which sounds like it's probably a bug. I'll look into it. Thanks!

DerekBeattie
Thanks for your answer Jimmy, quite helpful, but I'm still confused about why the line <%=Html.ValidationMessage(ViewData.ModelMetadata.PropertyName, "*") %> is not displaying a validation error...
Jonathan Sewell
A: 

Are you using Ajax.BeginForm or Html.BeginForm? I just read this which explained my problem and yours too if you're using Ajax.BeginForm..

RailRhoad
A: 

I just ran into what I believe is the same issue. My ValdationMessage works fine outside the template but within the template it is never called with client side validation. If I do a submit it does validate. Anyone any ideas?

Trevor