Fritz Fritz - 1 month ago 3x
ASP.NET (C#) Question

How to make Action accept List for a Model? (ASP.NET MVC 5)

I am able to successfully accept one entry to my database. But, the rest of the entries are not from my dynamically added fields.

Here is my Create for Sibling:

public ActionResult Create(List<sibling> siblings)

if (ModelState.IsValid)
foreach(sibling x in siblings)
return RedirectToAction("Index");
return View(siblings);

Here is my Sibling model:

public partial class sibling
public int sibling_id { get; set; }
public int child_id { get; set; }
public Nullable<int> age { get; set; }
public string gender { get; set; }

public virtual child child { get; set; }

This is my Create.cshtml:

@model dummyApp.Schema.TestModels.sibling

ViewBag.Title = "Create";

@section Scripts{
<script type="text/javascript">

$(document).ready(function () {
//var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).on("click", function (e) { //on add input button click
//if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-group">\
<p>Child ID: <input type="number" name="siblings[' + x + '].child_id"/></p> \
<p>Age: <input type="number" name="siblings[' + x + '].age"/></p> \
<p>Gender: <input type="text" name="siblings[' + x + '].gender"/></p> \
<a href="#" class="remove_field">Remove</a> \
</div>'); //add input box

$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;


@using (Html.BeginForm())

<div class="form-horizontal">

<div class="input_fields_wrap">
<button class="add_field_button btn btn-info">Add More Fields</button>
<div class="form-group">
<p>Child ID: <input type="text" name="siblings[0].child_id" /></p>
<p>Age: <input type="text" name="siblings[0].age" /></p>
<p>Gender: <input type="text" name="siblings[0].gender" /></p>

<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />


@Html.ActionLink("Back to List", "Index")


Your initial value of x is 1 and you are doing x++ before passing it to the dynamic html which you create in javascript; which will render elements as siblings[2].child_id. This breaks the continuity of index as aiblings[1] is missing and model binder will stop binding when it reaches a break in the sequence.

As a solution,