Html.Hidden builds wrong value data in MVC 2 app

狂风中的少年 提交于 2019-12-11 08:45:43

问题


I am using an id value that I pass in a hidden field. When the user submits the form I need the hidden field for my update. After the update, a new value is placed in the hidden field in the model and sent back to the view. What seems so strange is the helper always uses the first value, never updates. For example, look at the following from the View:

<%: Html.Hidden("MyId",Model.MyId)  %>
<%: Model.MyId %>

First time in a look at the source in the browser yields:

<input type="hidden" id="MyId" name="MyId" value="1" />
1

** submit back to controller and model updates the MyId property to 2.

Back at the browser I now find:

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

The very same model property has different values! The helper method is somehow grabbing it from a prior model instance or something?

Any help greatly appreciated on what I am not understanding. BTW..get the same behavior with Html.TextBox and Html.TextBoxFor.

Thanks.


回答1:


That's how HTML helpers work and it's by design. When binding they will first look at the value in the GET/POST request to see if the value is present and after that in the model. If a value is found in the request they will simply ignore the value you set in the model.

Normally you are not supposed to modify the data sent in the request inside your controller action. But if anyhow you decide to do it you will need to either roll your own helper or simply:

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


来源:https://stackoverflow.com/questions/3794773/html-hidden-builds-wrong-value-data-in-mvc-2-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!