【问题标题】:TextBoxFor is not refreshing after postbackTextBoxFor 在回发后不刷新
【发布时间】:2013-12-10 17:50:10
【问题描述】:

我可能在某个地方犯了一个愚蠢的错误。感谢您在以下方面的帮助。
我有一个带有单个可编辑字段的示例 MVC3 应用程序,该字段使用 TextBoxFor 方法显示给用户。在 Index(POST) 操作中,我更改了值,但它仍然保持不变。我究竟做错了什么?

我的代码:
型号:

public class TestModel
{
    public string Name { get; set; }
}

查看:

using (Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Name)
    <input type="submit" />
}

控制器:

public ActionResult Index()
{
    return View("Index", new TestModel() { Name = "Before post" });
}

[HttpPost]
public ActionResult Index(TestModel model)
{
    model.Name = "After post";
    return View("Index", model);
}

如果我将 TextBoxFor 替换为 TextBox 或 DisplayTextFor 那么它可以正常工作。

【问题讨论】:

  • 您确定正在调用 HttpPost Index 吗?
  • @rhughes 是的。首先,它适用于 TextBox 而不是 TextBoxFor。其次,我刚刚在两个动作和视图中都设置了断点,按下“提交”并看到 HttpPost Index 被触发,然后在视图中设置了一个断点。

标签: c# asp.net-mvc


【解决方案1】:

我相信在设置新值之前,您必须在 [HttpPost] 操作中调用 ModelState.Clear()

根据这个答案,有很好的解释:How to update the textbox value @Html.TextBoxFor(m => m.MvcGridModel.Rows[j].Id)

也看到这个:ASP.NET MVC 3 Ajax.BeginForm and Html.TextBoxFor does not reflect changes done on the server 尽管您似乎没有使用Ajax.BeginForm,但行为是相同的。

包括@Scheien 建议的示例:

[HttpPost]
public ActionResult Index(TestModel model)
{
    ModelState.Clear(); 
    model.Name = "After post";
    return View("Index", model);
}

【讨论】:

  • 已确认。在为 model.Name 设置新值之前添加 ModelState.Clear() 确实允许更新视图。
  • 现在我已经改变了我对 MVC 工作原理的理解......将在阅读结束后接受答案:)
  • 我在不知不觉中做了几个申请 :) 谢谢。
  • 不客气@Jim,我也得研究一下!然后我遇到了达林的回答,这让我记得我以前经历过这个,但是如果没有“为什么”,我无法给你答案。
猜你喜欢
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多