[RESOLVED]validation for List<string> in the model

Here
is a simple list in the inputs

public
class
Inputs

  {

    [Required(ErrorMessage="Must
enter a value"
)]

public
List<string>
PlacesVisited {
get;
set;
}

  }

@

 The View:

using
(Html.BeginForm())

{for
(
int
i = 0; i < 3; i++)

    {       
<p>@Html.TextBox("PlacesVisited", null, new
{ @id = "PlacesVisited" + i })</p>

            }

}

The problem is when the view rendered only the first input element has validation attributes.  I need PlacesVisited2 and PlacesVisited3 all have the same
data-val-required

attributes.  Maybe I cannot validate this way in my view? or I it just does not work for html element with the same names?

<form
action="/"
method="post">       
<p><input
data-val="true"
data-val-required="Must
enter a value"
id="PlacesVisited0"
name="PlacesVisited"
type="text"
value=""
/></p>      

<p><input
id="PlacesVisited1"
name="PlacesVisited"
type="text"
value=""
/></p>    

<p><input
id="PlacesVisited2"
name="PlacesVisited"
type="text"
value=""
/></p>

</form>

Browser post Key value pair i.e. name of the input control and value entered in it to server, so you need to write indexed name field for list binding

for (int i = 0; i < 3; i++)

    {        <p>@Html.TextBoxFor(m=> m[I])</p>

    }

See–

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

As far as your validation is concerned, it doesn’t help much as your looking for some values in the collection but your object is initialized with no item it will return count as 0 but it will still be valid.

In order to achieve validation, you need to implement your own class inheriting from Required attribute and check for item exist in the collection.

I realized the view engine probably inferred the [required] attributes on a list the most reasonable way.

Thanks a lot.   

Leave a Reply