Multiple textboxfor, same model. ValidationMessageFor not working

1.9k views Asked by At

I'm not getting all my textboxes's validation to work. Only while using "one" at a time. I'm trying to use the same model property for of my variations. Does anyone know a solution to this, or a better way of doing this?

@Html.Hidden("AggKPIID", item.AggKPIID)
@if (item.Värde.ToString() == "-1" || item.Värde.ToString() == "0")
{                   
  @Html.TextBoxFor(modelItem => item.Värde, new { Value = "", Name = "Värde", @class = "kpiTextbox kpiTextbox-edit", @id = "tb"+Id })
  <br />
  @Html.ValidationMessageFor(modelItem => item.Värde)
}
else
{
  @Html.TextBoxFor(modelItem => item.Värde, new { @class = "kpiTextbox kpiTextbox-edit", @id = "tb" + Id })
  <br />
  @Html.ValidationMessageFor(modelItem => item.Värde)
}    
@Html.Hidden("Tidsperiod", item.Tidsperiod)
@Html.Hidden("Id", Id)
2

There are 2 answers

3
AudioBubble On BEST ANSWER

You have not shown the complete code but it appears you are rendering this in a foreach loop. This will generate duplicate id attributes (invalid html) and name attributes so it wont post back to your collection anyway. Because the name attributes are all the same, the associated validation errors cannot be matched up. Change you view to use a for loop (the model needs to be IList<T> or alternatively you can use a custom EditorTemplate. Note I don't understand what you if statement is doing (it makes no sense) and if you want to change the value of Värde to an empty string if its value is 0 or -1, then you do that in the controller before you pass the model to the view.

for(int i = 0, i < Model.Count; i++)
{
  @Html.HiddenFor(m => m[0].AggKPIID)
  @Html.TextBoxFor(m => m[0].Värde, new { @class = "kpiTextbox kpiTextbox-edit" })
  @Html.ValidationMessageFor(m => m[0].Värde)
  @Html.HiddenFor(m => m[0].Tidsperiod)
  @Html.HiddenFor(m => m[0].Id)
}

and always used strongly types helpers and don't try to update the name attribute (not that new { Name = "Värde" } would do anything anyway)

1
beautifulcoder On

You should be able to define it only once

@{var attrs = null;}
@if (item.Värde.ToString() == "-1" || item.Värde.ToString() == "0")
{
    attrs = new { Value = "", @class = "kpiTextbox kpiTextbox-edit", @id = "tb" + Id };
}
else
{
    attrs = new { @class = "kpiTextbox kpiTextbox-edit", @id = "tb" + Id };
}
@Html.TextBoxFor(modelItem => item.Värde, attrs)
<br />
@Html.ValidationMessageFor(modelItem => item.Värde)

I also don't recommend setting Name.