views:

732

answers:

2

I was working on migrating MVC1 app to MVC2 today and i have come across a problem while changing the ValidationMessage to ValidationMessageFor implementation.

The below is the selectlist in my View

<%=Html.DropDownListFor(model => model.SecurityQuestions[0].Question,  "Some Security question", new { @class = "form_element_select" })%>

The below code works fine and i can see the validation message came from modelstate.

<%= Html.ValidationMessage("SecurityQuestions_0__Question")%> 

but this one does not work:

<%= Html.ValidationMessageFor(model => model.SecurityQuestions[0].Question)%>

SecurityQuestions is a generic list in my model

public List<SecurityQuestion> SecurityQuestions { get; set; }

Is this somewhat a bug in "ValidationMessageFor" or am i missing something here?

I have previously asked this question on asp.net forums.

+1  A: 

The problem is that ValidationMessageFor only uses the last property name as validation message key.

In your case this means that:

<%= Html.ValidationMessageFor(model => model.SecurityQuestions[0].Question) %>

equals

<%= Html.ValidationMessage("Question") %>

and not what you thought it would. Unfortunately in this case you will have to use the non-strong typed helper to have the whole string as it should be.

Robert Koritnik
<%= Html.ValidationMessage("Question") %> will not work as the rendered client ID output of Html.DropDownListFor(model => model.SecurityQuestions[0].Question... is SecurityQuestions_0__Question and realize that you are displaying multiple indexes of a generic list in the view.
Murat
@Murat: I know it doesn't work, that's why I suggested you use non-strong-typed helper for this particular case.
Robert Koritnik
Since SecurityQuestions_0__Question is a rendered output for the dropdownlist, Html.ValidationMessageFor should also render the same client id. Do you think this is a bug or something?
Murat
A: 

You can add error you want to see to ModelState, under key that is generated by ValidationMessageFor. Sure its a hack, but the fastest way to go. And it doesnt add any ugly "SecurityQuestions_0__Question" to your markup.

Yaroslav Yakovlev