views:

144

answers:

2

I have a problem with setting validation message. i have two Model in one control and both Model have same property "amount".

So setting validation for one Model.amount will reflect to other Model.amount as well. I have tried to pass different ids to both but not working.

<%= Html.TextBox("amount", Model.amount, new { id = "Pamount" })%>
    <%=Html.ValidationMessage("Pamount", " ")%>
<%= Html.TextBox("amount", Model.amount, new { id = "Eamount" })%>
    <%=Html.ValidationMessage("Eamount", " ")%>

and in action I am setting

if (obj.amount.ToString() == "0")
            modalState.AddModelError("Pamount", "");

but the validation is applied to Eamount as well

What should I do?

A: 

I think that when adding a model error, you access the field by name, not ID. So you would want to do

ModelState.AddModelError("amount", "");

Additionally, I would recommend giving the text boxes different names so that you don't add an error to both of them when only one is causing the error which could cause some confusion.

dhulk
A: 

The validation highlighting is applied based on the control's name. The name must reflect the property name in order for model binding to work. Therefore, you cannot have two controls with the same name and have the validation highlighting work correctly. So you need to give the controls different names. There are two ways that you can do this:

  1. Create a presentation model with two different properties for the different amounts. Transform the presentation model to/from the actual objects you are updating when displaying the form or handling a post, respectively.

  2. Create a single model with sub properties for both objects, and then access the two amounts using dot notation.

Like this:

<%= Html.TextBox("Foo.amount", Model.Foo.amount, [...]
<%= Html.TextBox("Bar.amount", Model.Bar.amount, [...]
Craig Stuntz