Non-sequantial list binding and BeginCollectionItem HTML Helper

Topics: ASP.NET MVC
Apr 8, 2012 at 3:03 PM
Edited Apr 8, 2012 at 3:08 PM

In ASP.NET MVC framework, for non-sequential list binding we need a random prefix for the form field name and also a hidden imput which indicates that item inside the collection. Here is an example on Phil's blog post about this topic:

<form method="post" action="/Home/Create">

    <input type="hidden" name="products.Index" value="cold" />
    <input type="text" name="products[cold].Name" value="Beer" />
    <input type="text" name="products[cold].Price" value="7.32" />
    
    <input type="hidden" name="products.Index" value="123" />
    <input type="text" name="products[123].Name" value="Chips" />
    <input type="text" name="products[123].Price" value="2.23" />
    
    <input type="hidden" name="products.Index" value="caliente" />
    <input type="text" name="products[caliente].Name" value="Salsa" />
    <input type="text" name="products[caliente].Price" value="1.23" />
    
    <input type="submit" />
</form>

Inside the framework, we do not have any HTML helper method to automate that process. A while back ago, Steve Sanderson wrote a blog post demonstrating a sample on non-sequantial list binding. He used a HTML helper method there called BeginCollectionItem which he created. He explained that helper with following words:

It’s a HTML helper I made that you can use when rendering a sequence of items that should later be model bound to a single collection. You give it some name for your collection, and it opens a new template context for that collection name, plus a random unique field ID prefix. It also automatically renders a hidden field, which in this case is called gifts.index, populating it with that unique ID, so when you later model bind to a list, ASP.NET MVC 2 will know that all the fields in this context should be associated with a single .NET object.

Usage:

@foreach (var item in Model) {

    <div class="editorRow">
        @using(Html.BeginCollectionItem("gifts")) {
            <div>
                Item: @Html.TextBoxFor(x => x.Name)
                Value: $ @Html.TextBoxFor(x => x.Price, new { size = 4 })
            </div>
        }
    </div>
}

I wonder if something like this can be baked into the framework. Any thoughts?

Apr 8, 2012 at 4:50 PM
This is no such feature in the framework today. Please open a feature request for it in the issue tracker.
Thanks!
Apr 8, 2012 at 5:03 PM

Ah, sorry Brad. I didn't know that non-existing features aren't discussed here. I'll do that.

Thanks!

Apr 8, 2012 at 5:05 PM

Here it is: http://aspnetwebstack.codeplex.com/workitem/49

Apr 8, 2012 at 5:11 PM

No, there's nothing wrong with asking if a feature exists. :) I was just confirmed that it didn't, and that opening an issue is the way it gets considered. :)

Apr 8, 2012 at 5:13 PM

Ah, totally get it now. Thanks :)