Html.TextBoxFor在POST操作中不显示更新的值

时间:2011-02-03 13:50:56

标签: asp.net-mvc

在我看来,我有

      <%:Html.LabelFor(model => model.IPAddress)%>

    <div class="editor-field">
        <%:Html.TextBoxFor(model => model.IPAddress)%>
        <%:Html.ValidationMessageFor(model => model.IPAddress)%>
    </div>

在我的控制器(post方法)中,我有这个

[HttpPost]
public ActionResult Manipulation(MyModel model){
  //I change modele here
  if(somthing)
    model.IPAddress="100.100.100.100";
  return View(model);
}

所以,我的问题是: 当我更改模型时,TextBoxFor不会更改其值。 当我从get方法到帖子时,TextBoxFor得到他的值,后来我无法改变TextBoxFor的值。 我调试,我的模型有新值,但TextBoxFor没有显示新值。

你能帮助我吗?

4 个答案:

答案 0 :(得分:15)

尝试:

ModelState.Clear();
return View(model);

如果不是结果!返回JSON结果,然后通过javascript更新

答案 1 :(得分:1)

不建议使用模型绑定,而是建议使用tryupdate调用。

[HttpPost]
public ActionResult Manipulation(FormCollection formCollection)
{
  MyModel model = new MyModel();

  if(TryUpdate(Model))
  {
      enter code here
  }

  if(somthing)
  model.IPAddress="100.100.100.100";
  return View(model);
}

查看我对我使用的一般结构的另一篇文章的回答。它从来没有让我失望,我相信它涵盖了从用户输入更新模型时的所有基础。

asp.net mvc controller post best practices

答案 2 :(得分:1)

Grok先生有一个类似的问题this网站。他已经找到了 ModelState.Clear()解决方案,但是想要解释它的工作原理。链接网站上排名最高的答案提出,html帮助程序的行为是一个错误,ModelState.Clear()是一种解决方法。但是,this网站上的bradwils说这种行为是设计的,并给出了以下解释:

我们使用编辑器的发布值而不是模型值的原因是模型可能无法包含用户键入的值。想象一下,在你的“int”编辑器中,用户输入了“dog”。您希望显示一条错误消息,其中显示“dog is not valid”,并在编辑器字段中保留“dog”。但是,你的模型是一个int:它无法存储“dog”。所以我们保留旧的价值。

如果您不想在编辑器中使用旧值,请清除模型状态。这就是旧的值存储和从HTML帮助程序中提取的地方。

尽管它是设计的,但对于开发人员来说这是非常意外的行为,不幸的是,需要与ModelState进行交互以满足常见的编程需求。

此外,清除整个ModelState可能会在其他区域引起意外问题(我认为在不相关的模型字段上进行验证)。非常感谢Peter Gluck(在Grok先生的页面中发表评论)提出更有限的 ModelState.Remove(“key”),感谢Toby J开发更方便的方法如果模型属性是嵌套的,你不确定键应该是什么。我也喜欢Toby的方法,因为它不依赖于字符串作为输入。

该方法有一些细微的变化,如下:

/// <summary>
/// Removes the ModelState entry corresponding to the specified property on the model. Call this when changing
/// Model values on the server after a postback, to prevent ModelState entries from taking precedence.
/// </summary>
/// <param name="model">The viewmodel that was passed in from a view, and which will be returned to a view</param>
/// <param name="propertyFetcher">A lambda expression that selects a property from the viewmodel in which to clear the ModelState information</param>
/// <remarks>
/// Code from Tobi J at https://stackoverflow.com/questions/1775170/asp-net-mvc-modelstate-clear
/// Also see comments by Peter Gluck, Metro Smurf and Proviste
/// Finally, see Bradwils http://forums.asp.net/p/1527149/3687407.aspx.  
/// </remarks>
public static void RemoveStateFor<TModel, TProperty>(
    this ModelStateDictionary modelState, 
    TModel model,
    Expression<Func<TModel, TProperty>> propertyFetcher
) {
    var key = ExpressionHelper.GetExpressionText(propertyFetcher);

    modelState.Remove(key);
}

答案 3 :(得分:0)

这是我发现的另一项工作。 而不是

@Html.TextBoxFor(m=>m.PropertyName)

这样做

@{
var myModel = Model;
}
@Html.TextBoxFor(m=>myModel.PropertyName)

如果您不想覆盖每个输入的默认行为,这可能很有用。

相关问题