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 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>
我想知道这种行为的原因,为什么会发生?
任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在更新值之前,只需添加 ModelState.Clear(),更新您的集合并返回它。
Before updating the values, just add ModelState.Clear(), update your collection and return it.
发布的值将覆盖视图模型值。在使用之前我已经有一个解决方法...
我想在你的情况下(我不完全确定你的对象是什么)类似于
The posted values will override the viewmodel values. I've had a workaround for this before using...
I guess in your case (and I'm not entirely sure what your object is) something along the lines of