I have a complex view model which contains a collection of other objects which are recursively rendered using editor and display templates.
Each of the items in the collection contains a form model that I would like to submit to a controller. Note, that I do not want to post the whole view model back again, just the form model.
My problem is that MVC renders each object as part of a collection, and I do not know how to bind a single object from the collection to an object in the controllers signature.
I know I can bind the whole lot back again using IEnumerable<Account>, but I am trying to create row level submissions rather than the whole page.
If anyone can point me in the right direction, or show me how this should be done in the MVC world (I come from web forms so have been somewhat spoiled) I’d appreciate it immensely.
I’ve included an example HTML fragment below and also the controller I would like to post to.
<form action="/Home/Index" method="post">
<input id="Accounts_0__AccountName" name="Accounts[0].AccountName" type="text" value="Account 1" />
<input id="Accounts_0__AccountId" name="Accounts[0].AccountId" type="hidden" value="dddf5ca7-f8de-4192-b63a-3548f891e293" />
<input type="submit" value="Submit" />
</form>
<form action="/Home/Index" method="post">
<input name="Accounts[1].AccountName" type="text" value="Account 2" />
<input id="Accounts_1__AccountId" name="Accounts[1].AccountId" type="hidden" value="95d75f76-16ef-4cf2-b1e7-5fad782002c5" />
<input type="submit" value="Submit" />
</form>
[HttpPost]
public ActionResult Index(Account accounts)
{
...
}
You could try setting the prefix in your editor template:
which if I am not mistaken should generate:
Obviously you realize that by doing this you end up with invalid HTML (you will have multiple elements with the same
id). A possible workaround would be to set the id manually:Another possibility would be to write a custom model binder for the Account type which would simply ignore the prefix when binding.