3

I have a Client dto that contains a bunch of fields and also contains a List.

Now, I can bind to it quite easy, and it will display the Client with all of his addresses. The thing is that the user can delete and add addresses dynamically.

I thought about adding forms surrounding each address but then I end up with inner forms and I know browsers don't play well with that.

Then I thought about using javascript but if an address is removed, I have to go over all addresses and change their indexes (addresses[0].City )because I noticed that if the indexes are not in order, and the action takes a ClientForm as a parameter, then only the addresses that have consecutive indexes and they start at 0 - will get in the ClientForm.Addresses list.

Any other solutions that are easy to implement ? Am I missing something ?

2 Answers 2

1

If you place a submit button with a different name on each of the addresses but no form tags, your outer form can check for the existence of a specific button and redirect to the right action (e.g edit address number 1, delete address 3 etc)

If you are using jquery validation one caveat is that the type of all the "child" submit buttons must be set to "cancel" so on pressing them validation does not occur.

HTH,

Dan

Sign up to request clarification or add additional context in comments.

1 Comment

not sure I understand what you mean by : "your outer form can check for the existance.... " a short example would be great.
1

For each address on your page provide a hidden form field called addresses.Index, this will take an integer value. The ASP.NET MVC model binder (in version 2 and above) will receive the multiple values of the addresses.Index form field, and use the integer values to determine which addresses[index].property field values logically belong together.

E.g.

addresses.Index = 0
addresses.Index = 3

Would prompt the model binder to go looking for...

addresses[0].City
addresses[0].Street
addresses[3].City
addresses[3].Street

...and populate an ICollection<Address> in your controller action with two elements.

Of course if you can delete and insert these records on your page, your Javascript will need to track the next index to use in a global variable, to avoid re-using the same index for multiple rows (i.e. don't just rely on the length of a table that holds the address elements, etc).

This solution described in further detail by Phil Haack here.

1 Comment

The index doesn't even need to be an integer, right? I was just using a unique value like the Id which happened to be an integer. That way I didn't have to assign an index on the client to make sure they stayed unique.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.