I'm new to MVC and I'm trying to figure out how to bind a dynamic list.
I followed instructions from this example and other examples in order to create my table. New items are successfully added to the table. However, on post back only the default item that was added to the list initially is available, none of the new ones.
These are my Models:
public class ItemModel {
public int ID { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
}
public class MainModel{
public List<ItemModel> Items { get; set; }
public MainModel(){
Items = new List<ItemModel>()
}
}
My view:
<table id="list">
<thead>
<tr>
<th style="width: 150px;">
@Html.DisplayNameFor(model => model.Items[0].Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Items[0].Description)
</th>
<th>
Delete
</th>
</tr>
</thead>
<tbody>
@Html.Partial("Item", Model)
</tbody>
</table>
Partial View:
@for (var i = 0; i < Model.Items.Count; i++) {
<tr>
<td>
@Html.TextBoxFor(model => model.Items[i].Name)
</td>
<td>
@Html.TextBoxFor(model => model.Items[i].Description)
</td>
<td>
<button class="btn" type="button" data-id="@Model.Items[i].ID" value="Delete"/>
</td>
</tr>
}
I'm using Ajax Post to add new items to the table:
$('.add').click(function () {
var action = "/Project/Add";
$.ajax({
url: action,
cache: false,
success: function (result) {
$("#list").find("tbody").empty().append($(result));
}
});
});
Controller Action:
public ActionResult Add() {
ItemModel item = new ItemModel();
try {
item.ID = ((MainModel)Session["MainModel"]).Items.LastOrDefault().ID + 1;
((MainModel)Session["MainModel"]).Items.Add(item);
} catch (Exception) {
return Json(null);
}
return PartialView("Item", Session["MainModel"]);
}
Can some please tell me what I'm doing wrong?
Thanks.