【问题标题】:MVC3: Updated value does not reflect in text box after postMVC3:发布后更新的值不会反映在文本框中
【发布时间】:2011-11-03 18:16:14
【问题描述】:

我正在我的页面上显示一组数据。我正在为每一行显示标签和文本框。

以下是我的视图中的示例代码:

@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 Action 中,我正在更新 Amount(比如增加 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" id=@("Persons_" + index + "__Amount") name="Persons[@index].Amount " value="@Model.Persons[index].Amount" ></input>

我想知道为什么会发生这种行为的原因?

任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net-mvc-3 postback


    【解决方案1】:

    在更新值之前,只需添加 ModelState.Clear(),更新你的集合并返回它。

    【讨论】:

      【解决方案2】:

      发布的值将覆盖视图模型值。在使用之前我有一个解决方法...

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

      我猜你的情况(我不完全确定你的对象是什么)类似于

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-07
        • 1970-01-01
        • 2019-09-10
        • 1970-01-01
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多