在我看来,我有
<%:Html.LabelFor(model => model.IPAddress)%>
<div class="editor-field">
<%:Html.TextBoxFor(model => model.IPAddress)%>
<%:Html.ValidationMessageFor(model => model.IPAddress)%>
</div>
Run Code Online (Sandbox Code Playgroud)
在我的控制器(post方法)中,我有这个
[HttpPost]
public ActionResult Manipulation(MyModel model){
//I change modele here
if(something)
model.IPAddress="100.100.100.100";
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是:当我改变模型时,TextBoxFor不会改变他的值.当我从get方法到帖子时,TextBoxFor得到他的值,后来我无法改变TextBoxFor的值.我调试,我的模型有新值,但TextBoxFor没有显示新值.
你能帮助我吗?
小智 16
尝试:
ModelState.Clear();
return View(model);
Run Code Online (Sandbox Code Playgroud)
如果不是结果!返回JSON结果,然后通过javascript更新
Grok 先生在这个网站上也有类似的问题。他已经找到了ModelState.Clear()解决方案,但想要解释它为什么起作用。链接站点上排名最高的答案提出 html 帮助程序的行为是一个错误,对此 ModelState.Clear() 是一种解决方法。但是,此站点上的bradwis表示该行为是设计使然,并给出了以下解释:
我们为编辑器使用发布值而不是模型值的原因是模型可能无法包含用户键入的值。想象一下,在您的“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 /sf/ask/124261931/
/// 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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6433 次 |
最近记录: |