How do you add, edit and delete items in a collection?
I have seen this question
How do I edit an IEnumerable<T> with ASP.NET MVC 3?
Which shows a good example of binding to a collection, but how do you go about adding and deleti开发者_JS百科ng items? I hope there is a solution which does not hit the server to add or delete an item, only a single post to the server to save all actions in bulk.
These can be kind of painful scenarios, depending on the complexity of the implementation (i.e. if you want inline edited in a grid and such).
Steve Sanderson has some really good posts on this, and he's also written a js library called Knockout that kind of rocks. I would recommend checking it out.
Add
One option is to use javascript to clone the last edit representation of an object and append it to that list so that there is another edit box for yet another one of the item. Besides cloning the html, it also needs to clear any contents, reset validation and increment the collection index number in the input IDs. It is not very clean however it works and does not hit the server.
Delete
This is more complicated because the model binder will insist that the collection index be unbroken. So you can't just delete one and then post the form back as there will be a hole in the collection index (ie 1, 2, 4 when deleting item at index 3). One way to handle this is to have a hidden ID field. On post back, validate what is being posted against what is in the data store and remove those not present. Delete would remove the item from the list and decrement the collection index number in the input IDs in any items beyond it. Again, messy. A potentially cleaner option is to hide the deleted item and have a hidden input field that signals deletion was requested. That way there is no concern over the collection index range having a break.
Hopefully, there is a better way to do this. I've written an abstracted way of doing this with javascript that relies on HTML class naming but it definitely feels somewhat unclean.
This question doesn't make sense... please describe your actual scenario.
IEnumerable is a server-side thing. There is no way to edit it without hitting the server.
But even if we dismiss your "does not hit the server" caveat, there is no way to edit an IEnumerable. That type is meant to be a read-only abstraction around some other data source. Where ever you got the IEnumerble from probably has some mechanism for add/edit/delete. Tell us where you IEnumerable is coming from, and we could probably point you towards that mechanism.
精彩评论