views:

114

answers:

3

I'm having trouble adding a validationmessage to my custom editortemplate, this is the line I am using (I've tried posting the entire template code but having no luck)

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

If I put the validationmessage for the model property outside of the template it works fine so I know the modelerror exists.

Any ideas?

A: 

I have an answer for you :)

You need to prefix the key of your property with the name of the property in the model.

For example, if your model looks like this:

public class MyModel
{
    public ChildModel Child { get; set; }
}

And you want to add an error message that the Child's template can see, you need to prefix the key of the error message as follows:

ModelState.AddModelError("Child.SomeKey", "Error message");

In your template view of ChildModel, display the error like this:

<%= Html.ValidationMessage("SomeKey")%>
Robert
A: 

I am in the same boat and the above answer doesn't have anything to do with the problem. My validation works fine outside the template but inside it won't get called. This is with client side validation only. If I do a submit it does get validated and I can see my error message. Has anyone had any luck adding a ValidationMessage in a EditorFor template?

Trevor
A: 

I use the strongly-typed html helpers.

Example

<div class="editor-label"><%= Html.LabelFor(model => model); %></div>
<div class="editor-field"><%= Html.TextBoxFor(model => model); %></div>
<div class="editor-error"><%= Html.ValidationMessageFor(model => model); %></div>

You could do the same thing without the strongly-typed helpers by using the Model ViewPage/Control property.

Josiah Ruddell