asp.net mvc - MVC make list property required on first loop only -


say have following list properties being rendered create view:

        @for (var = 0; < model.sitesplits.count(); i++)         {             <div class="clearfix"></div>             <div class="form-group">                 @html.labelfor(model => model.sitesplits[i].costcode, htmlattributes: new {@class = "control-label col-md-3"})                 <div class="col-md-9">                     @html.editorfor(model => model.sitesplits[i].costcode, new {htmlattributes = new {@class = "form-control"}})                 </div>             </div>              <div class="clearfix"></div>             <div class="form-group">                 @html.labelfor(model => model.sitesplits[i].splitpercentage, htmlattributes: new {@class = "control-label col-md-3"})                 <div class="col-md-9">                     @html.editorfor(model => model.sitesplits[i].splitpercentage, new {htmlattributes = new {@class = "form-control"}})                 </div>             </div>         } 

this results in x3 cost code , split percentages passed controller in list on post.

i've put required annotation on costcode , splitpercentage in view model, resulting in 3 of split/codes being required.

is there way of making costcode , splitpercentage required on first loop , have ignore validation second 2 merely optional?

to directly answer question, include addition property in model say

public bool isrequired { get; set; } 

and use foolproof [requirediftrue] or similar validation attribute on other properties

[requirediftrue("isrequired")] public string costcode { get; set; } 

and in method, populate sitesplits collection 3 default objects, setting first 1 isrequired = true; , include hidden input isrequired property.

@html.hiddenfor(m => m.sitesplits[i].isrequired) 

however, makes no sense in relation last question have indicated want between 1 , 3 items. if user added 3, last 2 not validated , saving invalid data.

a better option allow user dynamically add new items required, can done using begincollectionitem helper or creating html template , copying , appending collection (and updating collection indexers) discussed in following answers

  1. post form array without successful
  2. submit same partial view called multiple times data controller?
  3. set class validation dynamic textbox in table

an example of using begincollectionitem included in this article

refer this dotnetfiddle working example using html template based on models posted in last question


Comments