I appear to be having a problem with ASP.NET MVC in that, if I have more than one form on a page which uses the same name in each one, but as different types (radio/hidden/e
This issue still exists in MVC 5, and clearly it's not considered a bug which is fine.
We're finding that, although by design, this is not the expected behavior for us. Rather we always want the value of the hidden field to operate similarly to other types of fields and not be treated special, or pull its value from some obscure collection (which reminds us of ViewState!).
A few findings (correct value for us is the model value, incorrect is the ModelState value):
Html.DisplayFor() displays the correct value (it pulls from Model) Html.ValueFor does not (it pulls from ModelState)ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model pulls the correct valueOur solution is to simply implement our own Extension:
///
/// Custom HiddenFor that addresses the issues noted here:
/// http://stackoverflow.com/questions/594600/possible-bug-in-asp-net-mvc-with-form-values-being-replaced
/// We will only ever want values pulled from the model passed to the page instead of
/// pulling from modelstate.
/// Note, do not use 'ValueFor' in this method for these reasons.
///
public static IHtmlString HiddenTheWayWeWantItFor(this HtmlHelper htmlHelper,
Expression> expression,
object value = null,
bool withValidation = false)
{
if (value == null)
{
value = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model;
}
return new HtmlString(String.Format("",
htmlHelper.IdFor(expression),
htmlHelper.NameFor(expression),
value));
}