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

查看:423
本文介绍了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.

例如

我有这样的code,只是作为一个测试:

I have this code, just as a test:

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

我觉得这两个隐藏字段将具有相同的值。
我做的是什么,值我第一次显示查看设置为1,然后提交后我增加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.

我在想什么?是*对于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请求你的修改将被忽略,张贴的值会被使用。

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天全站免登陆