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?
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.