Asp.net mvc 隐藏表单元素问题-asp.net mvc
我在控制器中创建一个强类型表单,如下所示: 返回视图(“BlaForm”,Bla) 在视图中,我使用如下内容: (一)Asp.net mvc 隐藏表单元素问题-asp.net mvc,asp.net-mvc,asp.net-mvc-2,Asp.net Mvc,Asp.net Mvc 2,我在控制器中创建一个强类型表单,如下所示: 返回视图(“BlaForm”,Bla) 在视图中,我使用如下内容: (一) 在控制器操作中,在发生验证错误时维护表单值。这似乎就是原因。但我还是明确地说:????也许我有点误解了生命周期 Html助手将始终在模型或ViewData中的值之前使用GET或POST请求中的值。这意味着,如果将Version=9发布到控制器操作中,并且在该操作中尝试将其值修改为10,则返回视图时,Html.Hidden帮助程序将使用发布的值,而不是模型中的值。唯一的解决方法是
在控制器操作中,在发生验证错误时维护表单值。这似乎就是原因。但我还是明确地说:????也许我有点误解了生命周期 Html助手将始终在模型或ViewData中的值之前使用GET或POST请求中的值。这意味着,如果将
Version=9
发布到控制器操作中,并且在该操作中尝试将其值修改为10,则返回视图时,Html.Hidden帮助程序将使用发布的值,而不是模型中的值。唯一的解决方法是自定义HTML帮助程序,或者简单地说:
<input id="Version" name="Version" type="hidden" value="<%= Model.Version %>" />
HTML helper将始终在ModelStateDictionary中查找值,然后在ViewData中查找值,然后使用提供给helper方法的value参数 其他两个地方在你的情况下
ModelState state = this.ViewData.ModelState["Version"];
state.Value; // this is the value out of the ModelStateDictionary
object value = this.ViewData["Version"]; // this is the value if set
// out of the ViewData Collection
ModelStateDictionary在模型绑定时获取其条目。如果您将版本作为操作方法参数,则Modelbinder(在您的情况下为DefaultModelBinder)将使用提供的get或post request值输入密钥版本
如果更改该值,请将其放入模型中,还必须更新ModelStateDictionary。
<input id="Version" name="Version" type="hidden" value="9" />
if (TempData["ViewData"] != null)
{
ViewData = TempData["ViewData"] as ViewDataDictionary;
}
<input id="Version" name="Version" type="hidden" value="<%= Model.Version %>" />
ModelState state = this.ViewData.ModelState["Version"];
state.Value; // this is the value out of the ModelStateDictionary
object value = this.ViewData["Version"]; // this is the value if set
// out of the ViewData Collection