3

This post asks this question but doesn't really give an answer, so I thought I would ask the question differently.

I have a page that renders a hidden value from the model:

<%=Html.Hidden("myName", model.myValue) %>

Since I am passing a value in the value parameter, you would think it would output that value, but it doesn't.

The code for rendering input fields has the following:

string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string));
tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : valueParameter), isExplicitValue);

Basically, if the ModelState (which contains posted values) contains a value for the "name" passed, it will use that value instead of your passed value to the helper method. In my case, I updated the model and my updated value wasn't outputted.

If I pass a value to a method, I expect that value to be rendered.

Am I missing something in this design or is it just wrong?

1 Answer 1

2

This is by design. Here is the intended flow:

  1. The user requests a certain URI.
  2. Your controller builds out a model.
  3. The view is rendered. The ModelState dictionary should be empty at this point, so the value you pass to Html.Hidden will be rendered. However, the feature in question is more directly related to user input, so consider the case of Html.TextBox("someName", Model.SomeValue)
  4. Now imagine the user enters some invalid data. If you have a client-side validation, this would be caught before the POST, but let's pretend you don't, or that the user has somehow circumvented it.

In this case, the action which handles the POST will return a ViewResult, causing the view from step 3 to be re-rendered. However, the user will see the value they input (so they can fix it) instead of the value from your model object. The idea here is that the data the user entered possibly cannot be represented as a value in Model.SomeValue, due to type safety. If Model.SomeValuewas of type integer, for example, and the user entered "ABC", the only way to re-render the user's data is to put it somewhere else. And that "somewhere else" is ModelState.

Re-displaying the user's invalid data allows the user to fix the data they entered and re-post the form.

Sign up to request clarification or add additional context in comments.

2 Comments

I agree for all input controls, but hidden is not a visible input control. So shouldn't hidden behave differently?
MVC can't know how your hidden input is used and set. Perhaps you have a JavaScript GUI control on the page which reads/sets a hidden input to communicate with the server? MVC treats all form elements consistently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.