ASP.Net MVC Html.HiddenFor 值错误 [英] ASP.Net MVC Html.HiddenFor with wrong value

查看:24
本文介绍了ASP.Net MVC Html.HiddenFor 值错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用 MVC 3,但我看到了一个非常奇怪的行为.

I'm using MVC 3 in my project, and I'm seeing a very strange behavior.

我正在尝试为模型上的特定值创建一个隐藏字段,问题是由于某种原因,该字段上设置的值与模型中的值不对应.

I'm trying to create a hidden field for a particular value on my Model, the problem is that for some reason the value set on the field does not correspond to the value in the Model.

例如

我有这个代码,只是作为测试:

I have this code, just as a test:

<%:Html.Hidden("Step2", Model.Step) %>
<%:Html.HiddenFor(m => m.Step) %>

我认为两个隐藏字段都具有相同的值.我的做法是,第一次显示View时将值设置为1,然后提交后将Model字段的值加1.

I would think that both hidden fields would have the same value. What I do is, set the value to 1 the first time I display the View, and then after the submission I increase the value of the Model field by 1.

所以,第一次渲染页面时,两个控件的值都是 1,但第二次渲染的值是这些:

So, the first time I render the page both controls have the value 1, but the second time the values rendered are these:

<input id="Step2" name="Step2" type="hidden" value="2" />
<input id="Step" name="Step" type="hidden" value="1" />

如您所见,第一个值是正确的,但第二个值似乎与我第一次显示视图时相同.

As you can see, the first value is correct, but the second value seems to be the same as the first time I display the View.

我错过了什么?*For Html 助手是否以某种方式缓存值?如果是这样,我该如何禁用此缓存?

What am I missing? Are the *For Html helpers caching the values in some way? If so, how can I disable this caching?.

感谢您的帮助.

推荐答案

这很正常,这就是 HTML 帮助程序的工作方式.他们首先使用 POST 请求的值,然后使用模型中的值.这意味着即使您在控制器操作中修改模型的值,如果 POST 请求中存在相同的变量,您的修改也将被忽略并使用 POSTed 值.

That's normal and it is how HTML helpers work. They first use the value of the POST request and after that the value in the model. This means that even if you modify the value of the model in your controller action if there is the same variable in the POST request your modification will be ignored and the POSTed value will be used.

一种可能的解决方法是从试图修改该值的控制器操作中的模型状态中删除该值:

One possible workaround is to remove this value from the model state in the controller action which is trying to modify the value:

// remove the Step variable from the model state 
// if you want the changes in the model to be
// taken into account
ModelState.Remove("Step");
model.Step = 2;

另一种可能性是编写一个自定义的 HTML 帮助程序,它将始终使用模型的值并忽略 POST 值.

Another possibility is to write a custom HTML helper which will always use the value of the model and ignore POST values.

还有一种可能:

<input type="hidden" name="Step" value="<%: Model.Step %>" />

这篇关于ASP.Net MVC Html.HiddenFor 值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆