I’ve been attempting to bind a view to a list of objects as described here Model Binding To A List
My problem is when the list is returned via a POST, the list contains the correct number of elements that I originally sent, but the values within the objects are coming back as if they were never set. Not sure what I missed to make the model binder parse correctly.
Here is my test code:
My model is:
IList<Test>
where Test is defined as:
public class Test
{
public int x;
}
In my TestController, I am using a method “Create” which has a postback:
public ActionResult Create()
{
List<Models.Test> testList = new List<Models.Test>() {
new Models.Test() { x = 5 }
};
return View(testList);
}
//
// POST: /Test/Create
[HttpPost]
public ActionResult Create(IList<Models.Test> tests)//Models.TestContainer tc)
{
return View(tests);
}
and the “Create” view’s code:
@model IList<ksg.Models.Test>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>TestContainer</legend>
@Html.EditorFor(x => x[0])
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
And finally, my editor template for the Test class:
@model ksg.Models.Test
@using ksg.Helpers
<div>
@Html.TextBoxFor(x => x.x)
</div>
As shown above, I send a list with 1 item with Test.x = 5, but when I breakpoint on Create(IList<Models.Test> tests), tests contains 1 object with x = 0.
Any ideas what I missed?
I have tried your code and problem is that
xinTestclass is field and not property, thus the default model binder cannot set value from posted form.Testclass should look like this:Then it works.