The reason you always get null
value is the model binder doesn't know how to bind the list of Objects. See below example:
public class CmaPartialModel
{
public List<DataItemWithLabel> DataItemsWithLabels { get; set; }
}
Then use it in you view:
@model CmaPartialModel
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
@using (Ajax.BeginForm("TestPost", new AjaxOptions { HttpMethod = "Post" }))
{
for(var i = 0; i < Model.DataItemsWithLabels.Count; i++)
{
@Html.LabelFor(m => m.DataItemsWithLabels[i].DataName)
@Html.TextBoxFor(m => m.DataItemsWithLabels[i].DataValue)
}
<input type="submit" value="Save" />
}
Finally, your action method should be like below:
public ActionResult TestPost(CmaPartialModel model)
{
return PartialView("Transaction", model);
}
Update
You also can use foreach
in your view like below:
foreach (var item in Model.DataItemsWithLabels.Select((value, i) => new { i, value }))
{
@Html.LabelFor(m => m.DataItemsWithLabels[@item.i].DataName)
@Html.TextBoxFor(m => m.DataItemsWithLabels[@item.i].DataValue);
}