0

First off, this is very similar to Collection of complex child objects in Asp.Net MVC 3 application? but none of the answers there actually answered this completely for me.

I have a Poll model that holds a list of PollItem models. My view is for creating new polls so the model passed in to the view is completely empty. So there are text boxes for the basic poll information, and then a lower section where the user can add/remove an arbitrary amount of poll items. I need to somehow bind those poll item textboxes to the list of PollItems.

@using (Html.BeginForm("CreatePoll", "Polls", FormMethod.Post, new { enctype = "multipart/form-data", id = "createPollForm", @class = "cmxform group" }))
    {
        @Html.TextBoxFor(x => x.Question, new { @class = "title-input full-width prominent", placeholder = "Enter Question Here" })
        <ul class="poll-info">
            <li>
                <p><label>Poll Opens</label></p>
                @Html.TextBoxFor(x => x.OpeningDate, new { id = "openingDatePicker" })
            </li>
            <li>
                <p><label>Poll Closes</label></p>
                @Html.TextBoxFor(x => x.ClosingDate, new { id = "closingDatePicker" })
            </li>
        </ul>
        <section class="description">
            <p><label>Description</label></p>
            @Html.TextAreaFor(x => x.Description, new { @class = "full-width", placeholder = "Enter a more detailed description of the poll here." })
        </section>

        <a class="button"><i class="ico"></i> Attach an object</a>

        <section class="module-questions">
            <ul>
            </ul>
            <span class="button link" onclick="addAnswer()"><i class="ico"></i> Add Answer</span>
        </section>
    }

The addAnswer() function appends a new textbox in a list item to the unordered list which would be bound to PollItem.Description, those are held in Poll.PollItems which is the list. There will probably be some other elements in the PollItem as well, besides Description.

I don't even really know where to start here as I have no idea how to bind textboxes that are being dynamically added and removed.

Community
  • 1
  • 1
Kyle Sawatsky
  • 175
  • 1
  • 10

2 Answers2

0

I would recommend you checking out the following blog post which illustrates how to achieve exactly that. It demonstrates the usage of a custom Html.BeginCollectionItem helper which takes care of generating proper names for the input fields which are added and removed dynamically.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I somehow missed the bits about dynamic adding and removing of items when I read that before. Now I feel silly. It ended up working perfectly. – Kyle Sawatsky Jun 03 '12 at 23:31