Skip to content Skip to sidebar Skip to footer

Create Dynamic Elements That Are MVC Format

I have 3 input boxes in an ASP.NET MVC application. Users can add up to 10 contacts to the page. They add extra rows by clicking the 'add row' button, and delete rows using the 'de

Solution 1:

Thank you GregH for your help! The article you posted was VERY helpful: haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Have a Class (forgot to post this earlier, but it was there)

    public class Contact
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
}

Properly Format NAMES (not ids) in HTML instead of "id=email1" we used "name = 1.email". We also did the same thing for id, but that wasn't the fix.

function addRow(tableID, idNumber) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type = "text";
    element2.id = "[" + idNumber + "].Name";
    element2.name = "[" + idNumber + "].Name";
    element2.className = "form-control";
    cell2.appendChild(element2);

Update the Controller by adding a new method

public ActionResult ExampleName(List<Contact> contacts)
    {

        var X = contacts;

        return View();
    }

Post a Comment for "Create Dynamic Elements That Are MVC Format"