how can the Controller detect changes to child entities/rows in a View?
What's the most appropriate approach to the following scenario?
I have two models:
- TimeSheet: Consisting of four properties:
DayStartTime
,DayEndTime
,BreakTime
,List<TimeSheetHours>
- TimeSheetHours: Consisting of four properties:
ClientId
,ProjectId
,HoursWorked
My time sheet view is strongly typed to a IEnumerable<TimeSheet>
list. This list contains 7 TimeSheet models, one for each day of the week Sunday-Saturday. This time sheet view uses an editor tempate to produce input fields for DayStartTime
, DayEndTime
, BreakTime
, for each of the days of week:
Each day contains开发者_如何学编程 a section for clients & projects. Clicking an "add" button fires an ajax function which calls a controller action to render a partial view dynamically inserting a row of controls (Client combobox, Project combobox, HoursWorked textbox) into the appropriate clients & projects section for that day:
I'm having a hard time understanding how I can update each timesheet model's List<TimeSheetHours>
when I add a new client/project row via the ajax call.
So in the end, when I submit to the controller for inserting the timesheet, I have everything thing I need for each timesheet model in the list I produced the view.
Any assistance would be much appreciated.
Thank you!
You will either have to massage the names of these elements before they're posted to look like how I have it below or in your ajax call pass in the index of the TimeSheet
and then create the name:
TimeSheetHours
Index = 0
<input type="text" id="TimeSheet[0]_TimeSheetHours[0]_DayStartTime"
name="TimeSheet[0].TimeSheetHours[0].DayStartTime" value="1" />
<input type="text" id="TimeSheet[0]_TimeSheetHours[0]_DayEndTime"
name="TimeSheet[0].TimeSheetHours[0].DayEndTime" value="2" />
<input type="text" id="TimeSheet[0]_TimeSheetHours[0]_BreakTime"
name="TimeSheet[0].TimeSheetHours[0].BreakTime" value="1" />
TimeSheetHours
Index = 1
<input type="text" id="TimeSheet[0]_TimeSheetHours[1]_DayStartTime"
name="TimeSheet[0].TimeSheetHours[1].DayStartTime" value="3" />
<input type="text" id="TimeSheet[0]_TimeSheetHours[1]_DayEndTime"
name="TimeSheet[0].TimeSheetHours[1].DayEndTime" value="4" />
<input type="text" id="TimeSheet[0]_TimeSheetHours[1]_BreakTime"
name="TimeSheet[0].TimeSheetHours[1].BreakTime" value="0" />
You're probably much better off intercepting the submit
event and iterating over each TimeSheetHours
html-represented element and assigning the name as a mask and then submitting the form. This should allow the model binder to reconstruct your List<TimeSheet>
with a populated List<TimeSheetHours>
property.
Here's a good tutorial on how to solve this issue of posting a collection: ASP.NET MVC 2 Model Binding for a Collection
精彩评论