hoetz
hoetz

Reputation: 2388

ASP.NET MVC3: Adding Textboxes with Jquery and binding to Model

I have created a View which prompts the user to input some records with an invoice number and save them to the DB. Now a new requirement came in, we must be able to save 1..N invoice numbers for one record. No problem in the database, but I cant find a clean way to change the view and the model. As of now I'm doing this:

 <div class="editor-label">
            @Html.LabelFor(x => x.InvoiceNumber1)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(x => x.InvoiceNumber1)
            @Html.ValidationMessageFor(x => x.InvoiceNumber1)
        </div>

To satisfy the new requirement I'd have to create a button of some kind which lets the user add additional textboxes (via qjuery) to the view. But how would I bind those dynamically added textboxes back to the model on the form submit?

Upvotes: 2

Views: 2062

Answers (2)

Matija Grcic
Matija Grcic

Reputation: 13381

Check http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx and http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ you use Sequential Indices but to be able to remove, or add rows using javacript you can use Non-Sequential Indices as explained in both links. Regards

Upvotes: 2

Zruty
Zruty

Reputation: 8667

Suppose your model is as follows:

// model
public class InvoiceModel
{
    public List<int> InvoiceNumbers { get; set; }
}

Now if you name your inputs InvoiceNumbers[0], InvoiceNumbers[1] etc., the values will be correctly bound to the InvoiceNumbers property of the model.

Upvotes: 2

Related Questions