2011-08-25 104 views
1

我正在显示我的页面上的数据集合。我为每一行显示标签和文本框。MVC3:更新后的值不会反映在文本框后

下面是我查看示例代码:

@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) 
    } 
} 

在POST操作,我更新量(说5增加)。

[HttpPost] 
    public ActionResult Persons(PersonList presenter) 
    { 

     for (int index = 0; index < presenter.Persons.Count; index++) 
     { 
      presenter.Persons[index].Amount += 5; 
     } 
     return View(presenter); 
    } 

此更新的金额未反映在页面上。 但是,如果我用下面的代码则正常显示,像

@Model.Persons[index].Amount 

或者

<input type="text" [email protected]("Persons_" + index + "__Amount") name="Persons[@index].Amount " value="@Model.Persons[index].Amount" ></input> 

我想这样的行为为什么会发生的原因是什么?

任何帮助,将不胜感激。

回答

2

发布的值将覆盖视图模型值。我已经解决类​​似的问题在使用前...沿

PersonCollection persons = (PersonCollection)ModelState["Persons"].Value.RawValue; 
persons[index].Amount += 5; 
ModelState["Persons"].Value = new ValueProviderResult(persons, "Persons", CultureInfo.InvariantCulture); 
5

线

ModelState["Field"].Value = new ValueProviderResult("NewValue", "Field", CultureInfo.InvariantCulture); 

我猜你的情况(我不完全相信你的目标是什么)事在更新值之前,只需添加ModelState.Clear(),更新您的集合并将其返回。