【问题标题】:MVC - change model's value in view on post [closed]MVC - 在帖子中更改模型值[关闭]
【发布时间】:2011-06-21 05:00:32
【问题描述】:

我有一个视图,它显示了模型中的一些数据。我有提交按钮,onClick 事件应该更改模型的值,并且我传递了具有不同值的模型,但我在 TextBoxFor 中的值与页面加载时的值保持不变。我该如何更改它们?

【问题讨论】:

  • 没有任何源代码不可能给出任何答案

标签: asp.net-mvc asp.net-mvc-2


【解决方案1】:

这就是 HTML 助手的工作方式,而且是设计使然。他们将首先查看已发布的数据,然后查看模型。例如,如果您有:

<% using (Html.BeginForm()) { %>
    <%= Html.TextBoxFor(x => x.Name) %>
    <input type="submit" value="OK" />
<% } %>

您发布到以下操作:

[HttpPost]
public ActionResult Index(SomeModel model)
{
    model.Name = "some new name";
    return View(model);
}

当视图重新显示时,旧值将被使用。一种可能的解决方法是从 ModelState 中删除值:

[HttpPost]
public ActionResult Index(SomeModel model)
{
    ModelState.Remove("Name");
    model.Name = "some new name";
    return View(model);
}

【讨论】:

  • 在非常相似的场景中尝试过.. 似乎不起作用。任何帮助将在这里得到赞赏 - stackoverflow.com/questions/12138552/…
  • 在 Darin 的回答中,这与 MVC4 和 Razor 完全相同。
  • 这对我帮助很大,谢谢!致结束这个问题的人:在判断这个问题是否值得之前,您需要知道这里问的是什么!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 2014-10-13
相关资源
最近更新 更多