I have an issue which I really just don't understand. I have a very simple model which has a List as a public member. Whenever my controller removes an element from the model on postback the TextBoxFor() HTML helpers do not seem to pick up the changes. These helpers appear to be caching something but I cannot put my finger on it.
A Demo/Repro can be found here: http://broken.azurewebsites.net
Repro
- Navigate to http://broken.azurewebsites.net
- Notice the 4 column values populated with zero based values
- Hit the "test" button to POST back the page where I remove the first item in the list
- Notice The "real" values are correct and the 0 element has been removed, however the problem here is with the values rendered via TextBoxFor(). I cannot figure out why it is rendering 0 still when that element no longer exists.
Models
public class ItemViewModel
{
public string Description { get; set; }
public decimal? Amount { get; set; }
}
public class TestViewModel
{
public TestViewModel()
{
Items = new List<ItemViewModel>();
}
public List<ItemViewModel> Items { get; set; }
}
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new TestViewModel();
for (var i = 0; i < 4; i++)
{
model.Items.Add(new ItemViewModel { Description = i.ToString(), Amount = i });
}
return View(model);
}
[HttpPost]
public ActionResult Index(TestViewModel model)
{
model.Items.RemoveAt(0);
return View(model);
}
}
View
@model Demo.Models.TestViewModel
@using (Html.BeginForm())
{
<table>
<thead>
<tr><td>Description</td><td>Amount</td><td>Real-Description</td><td>Real-Amount</td></tr>
</thead>
<tbody>
@for (var i = 0; i < Model.Items.Count; i++)
{
var ii = i;
<tr>
<td>@Html.TextBoxFor(m => m.Items[ii].Description)</td>
<td>@Html.TextBoxFor(m => m.Items[ii].Amount)</td>
<td>@Model.Items[ii].Description</td>
<td>@Model.Items[ii].Amount</td>
</tr>
}
</tbody>
</table>
<button>Test</button>
}