Reputation: 352
I am showing a collection of data on my page. I am showing label and Textbox for each row.
Below is the sample code from my View:
@using (Html.BeginForm())
{
<input type="submit" value="Ok" />
@for (int index = 0; index < Model.Persons.Count; index++ )
{
@Model.Persons[index].Name
@Html.TextBoxFor(m => Model.Persons[index].Amount)
}
}
In the Post Action, I am update Amount (say increasing by 5).
[HttpPost]
public ActionResult Persons(PersonList presenter)
{
for (int index = 0; index < presenter.Persons.Count; index++)
{
presenter.Persons[index].Amount += 5;
}
return View(presenter);
}
This updated amount is not reflected on the page. However if I use below code then it is shown properly, like
@Model.Persons[index].Amount
Or
<input type="text" id=@("Persons_" + index + "__Amount") name="Persons[@index].Amount " value="@Model.Persons[index].Amount" ></input>
I would like to the reason for such behaviour that why is it happening?
Any help would be appreciated.
Upvotes: 1
Views: 2832
Reputation: 1256
Before updating the values, just add ModelState.Clear(), update your collection and return it.
Upvotes: 5
Reputation: 791
The posted values will override the viewmodel values. I've had a workaround for this before using...
ModelState["Field"].Value = new ValueProviderResult("NewValue", "Field", CultureInfo.InvariantCulture);
I guess in your case (and I'm not entirely sure what your object is) something along the lines of
PersonCollection persons = (PersonCollection)ModelState["Persons"].Value.RawValue;
persons[index].Amount += 5;
ModelState["Persons"].Value = new ValueProviderResult(persons, "Persons", CultureInfo.InvariantCulture);
Upvotes: 2