How is a list persisted back to the controller in MVC3 with Razor?
I'm trying to do a simple messaging page, and would like a list of recipients that could be modified in place.
So for example: So the user is at a document, and wants to message other users of that document.
Click message button
Message screen comes up with list of recipients populated already from the ViewModel
User clicks X to remove one or mo开发者_如何学JAVAre recipients
User types message
User clicks Submit
Controller receives a model with the message filled in and a list of recipients
How do I ensure that list is the modified list?
Get your html to look something like this:
<form ... blah blah ...>
<ul>
<li>
recipient 1
<input type="hidden" name="theParameterInControllerAction.Recipients[0]" value="1" />
</li>
<li>
recipient 2
<input type="hidden" name="theParameterInControllerAction.Recipients[0]" value="2" />
</li>
...
</ul>
<textarea name="theParameterInControllerAction.Message" ... blah blah ... ></textarea>
<input type="submit" value"click me" />
</form>
Set up your model and controller to accept the form according to how I laid out those name
attributes. Then, use javascript to remove li as you need in place. Then, you have two choices:
- find an MVC model binder that binds to lists even if the indices are out of order (because you may remove recipient 2 and then your controller will see 0,2,3,4,...)
- use javascript to intercept the post event of that form and re-write the
name
attributes of the hidden inputs above
Hope that was clear, was kind of rushing while I wrote it.
精彩评论