c# - Model Validation on collection with checkbox fails when checkbox not rendered -


when index view display 2 people , none of them selected model validation works correctly due minlengthattribute in .net 4.5.

now comes custom logic in ui. when 1 person displayed in index view need no checkbox check it. customer can directly press submit button. try manually fill selectedids array see @else clause.

but code: model.selectedids = new int[]{ item.personid};

does not work, viewmodel.selectedids property on server side action {int[0]}

how can still assign 1 person id selectedids array?

view

   @model listtest.models.peoplelistviewmodel   @{     var hasmorethanoneperson = @model.people.count > 1;    }  @html.beginform("save", "home") {  @html.validationsummary(false)  <table>     @foreach (var item in model.people)     {         <tr>             @if (hasmorethanoneperson)             {                 <td>                     <input type="checkbox" name="selectedids" value="@item.personid" />                 </td>             }             else             {                 model.selectedids = new int[]{ item.personid};             }              <td>                 <input type="text" value="@item.name" />             </td>         </tr>     } </table> <input type="submit" value="save" /> } 

viewmodel

public class peoplelistviewmodel     {         public peoplelistviewmodel()         {             selectedids = new int[] { };         }          [minlength(1, errormessage = "minimum 1 person must selected!")]         public int[] selectedids { get; set; }          public list<person> people { get; set; }     } 

controller

public actionresult index() {      var people = new list<person> {         new person { name = "horst", personid = 10 },          new person { name = "michael", personid = 20}      };      return view(new peoplelistviewmodel { people = people }); }  [httppost] public actionresult save(peoplelistviewmodel viewmodel) {      if (modelstate.isvalid)     {       }      viewmodel.people = new list<person> { new person { name = "horst", personid = 10 }, new person { name = "bernarnd", personid = 20 } };      return view("index", viewmodel); } 

you might consider rendering hidden field in case ensure value sent server:

@if (hasmorethanoneperson) {     <td>         <input type="checkbox" name="selectedids" value="@item.personid" />     </td> } else {     @html.hidden("selectedids", item.personid) } 

but better approach handle on server - means if there's no value assigned in view model fetch backend because user didn't have chance modify value in ui since there no corresponding input element manipulate.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -