简体   繁体   中英

Html.EditorFor losing data

I'm currently working on a large project which has a Timesheet class containing a list of TimesheetEntries. There is an edit page for this that looks like:

<!-- Other timesheet properties -->
@Html.EditorFor(model => model.TimesheetEntries)

This works great, I get a row for each timesheet entry. When I save the timesheet (POST to the server) a custom model binder strips out empty rows before passing a Timesheet to the controller, in other words the Timesheet can contain fewer rows than the POST data.

If there is a validation error I redisplay the edit page and this is where the problem arises.

If model.TimesheetEntries contains n records Html.EditorFor() reproduces the first n rows from the POST data (including the empty rows) rather than creating HTML for the data I pass it! This means I lose a number of rows at the bottom of the table which is clearly unwanted.

Can anyone explain why this is happening or even better tell me how to get EditorFor to work as I expect?

Here's a picture to describe the process:

时间表流程

You may want to take a look at the answer provided in this post Asp:net MVC 3: @Html.EditorFor a subcollection of my model in a template? It may help.

Turns out Html.EditorFor looks in ModelState before using the values you pass it... So to get it to pick up the values I passed it I needed to clear the relevant ones out of ModelState first, ugh.

This question/answer covers it in more detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM