tags:

views:

152

answers:

3

The best public example that I can think of off the top of my head would be the amazon shopping cart. Where you have a page that displays multiple distinct records that can have multiple distinct fields updated.

I can't put each one in a form tag because the user may modify more than one record and then submit.

I can't just update all the records that I get back because:
1. Performance
2. Auditing
3. If someone changed the record that the user 'didn't change' when they were viewing the page and then the user submits those changes would be overwritten.

So how to best handle getting the data back and then getting which records where changed out of that?

Is that clear?

+1  A: 

Generate your form in a repeater, and append an ID to the form elements that increments with each new form. Save the number of repeated form elements in a hidden field. Then in your controller, read the value of this hidden field - that'll be the number of forms to read. Then, in a loop, retrieve each form's fields by specifying the name of the field, plus the loop index appended to the name, as the key.

You can use some javascript logic to detect when a form's value changes, and update a hidden field in that form's section if that occurs; or you can hide the original values inside a hidden field with each form section (although I don't recommend this as too many fields / forms will bloat your page).

Erik Forbes
I think I like that. The hidden field + JS update to tell when a record is changed is what I didn't think of.I think I would even be able to write a model binder to get a collection back as an action parameter.
Andrew Burns
A model binder would be a good way to go, definitely. :) Let us know how it goes.
Erik Forbes
+1  A: 

one (but not necessarily the best) approach is to store which items are changed in a js-variable or something on the client side as they are changed, and then only send the data that is actually different from what the user recieved.

and as Erik stated, you could use hidden form elements to make sure that it works without js as well.

Tomas Lycken
This is a good solution as well - and if you include the contents of my answer, then you have a solution that reduces the traffic in the common case, yet degrades gracefully in the uncommon case of a user who doesn't have JS enabled.
Erik Forbes
+2  A: 

Use binding! Don't be iterating the form collection in your actions.

Steve Sanderson wrote a blog post about how to do it. I wrote a blog post on how to do it with MvcContrib.FluentHtml. Both posts are very detailed and include downloadable code.

Tim Scott