mercredi 11 février 2015

asp.net webforms model binding a checkbox to boolean array in a Gridview EditItemTemplate

I have a Gridview EditItemTemplate containing individual checkboxes for the days of the week. Seven in total.

Is it possible, or, is there a nice way to do model binding to save the selected value of these checkboxes to an array of bools in my GridView UpdateMethod?


With the code here I get a HttpException when I hit the Edit Button on a row of my Gridview:


DataBinding: 'WebTest3.Data.MyModel' does not contain a property with the name 'true'.


GridView Update method :



public void EditSchedule(int ScheduleId)
{

MyModel model = new MyModel();


TryUpdateModel(model);
if (ModelState.IsValid)
{
_repo.UpdateSchedule(model);
_repo.Save();
}


Response.Redirect(Request.RawUrl);


My simplified model looks like:



public class MyModel
{
public int ScheduleId { get; set: }
public string[] Days { get; set; }
}


My markup looks like:



<EditItemTemplate>
<tr>
<td class="cell cellButtons">
<asp:Button ID="InserButton" runat="server" Text="Insert" CommandName="Update" CausesValidation="true" validationgroup="GridGroup" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="false" />
</td>

<td class="cell cellDay">
<asp:CheckBox ID="cbM" runat="server" checked='<%# BindItem.Days[0] %>' />
</td>

<td class="cell cellDay">
<asp:CheckBox ID="cbT" runat="server" checked='<%# BindItem.Days[1] %>' />
</td>

<td class="cell cellDay">
<asp:CheckBox ID="cbW" runat="server" checked='<%# BindItem.Days[2] %>' />
</td>
.
.
.
</tr>
</EditItemTemplate>


The checkboxes display ok on my page and hit the EditMethod ok (with the correct ScheduleId..nice)) if I use 'Item' instead of 'BindItem' :



<asp:CheckBox ID="cbW" runat="server" checked='<%# Item.Days[0] %>' />


But then of course won't save when I do the TryUpdateModel(model) thing.


If I have separate, single bool values for each day of the week in my model then it all works. I just thought it might be straighforward to do with collections also. With the collections I can simplify my markup with repeaters and that kind of thing.


Would a checklist instead of checkboxes do anything for me ?


Thanks in advance for your wisdom,





Aucun commentaire:

Enregistrer un commentaire