sukesh
sukesh

Reputation: 2523

How to use @Html.ValidationMessageFor for @Html.TextBox

The following works fine:

@Html.TextBoxFor(x => x.Residence.Rent, new { @class = "form-control"" })
@Html.ValidationMessageFor(x => x.Residence.Rent, null, "span")

But the need is to send a list of objects to the controller. So I have tried this:

@for(int index = 0; index < Model.ResidencesList.Count; index++)
{
    @Html.TextBox("ResidencesList[" + index + "].Rent", ResidencesList[index].Rent, new { id="", @class = "form-control"" })
    @Html.ValidationMessageFor("ResidencesList[" + index + "].Rent", null, "span")
}

which renders the mark up as:

<input class="form-control" name="ResidencesList[0].Rent" type="text" value="">
<span class="field-validation-error" data-valmsg-for="ResidencesList[0].Rent" data-valmsg-replace="true">
   <span>undefined</span>
</span>

The validation doesn't fire on submit and also the message "undefined" shows when I select the textbox.

Upvotes: 0

Views: 224

Answers (1)

Serge
Serge

Reputation: 43850

try to replace

  @Html.TextBox("ResidencesList[" + index + "].Rent", ResidencesList[index].Rent, new { id="", @class = "form-control"" })
 @Html.ValidationMessageFor("ResidencesList[" + index + "].Rent", null, "span")

with

@Html.TextBoxFor(model=> model.ResidencesList[index].Rent, new {  @class = "form-control"})
 @Html.ValidationMessageFor( model=> model.ResidencesList[index].Rent, "", new { @class = "text-danger" })

Upvotes: 1

Related Questions