MVC Hidden field via HTML Helper in Form Post issue

后端 未结 1 1474
灰色年华
灰色年华 2021-01-01 06:48

I have an issue when using a hidden field in an MVC Form Post. When the hidden field is generated via a HTML Helper it won\'t preserve it\'s value during the postback. But w

相关标签:
1条回答
  • 2021-01-01 07:24

    Although not obvious and I found it difficult to find many articles on this subject to clarify it for me in the past the default behaviour in ASP.NET MVC is the following:

    If you are using HTML Helpers and you are rendering the same View in response to a POST it is assumed that you are responding to failed form validation. Therefore the values before being set in the POST will always be rendered back in the view from ModelState.

    You have a few options:

    1. ModelState.Clear(); in your post. Not recommended as the framework has not been designed this way.
    2. Use the Post-Redirect-Get pattern and only display validation failure, as the framework was designed (as @StephenMuecke mentions).
    3. If you are not bothered about validation do not use HtmlHelpers
    4. Use Request.Form values instead and remove the SomeViewModel someViewModel parameter. Wouldn't recommend this as you lose all benefits of model binding.
    5. Use ModelState.Remove for the specific field, again not recommended.

    The best article I found on this was article from Simon Ince in 2010:

    ASP.NET MVC’s Html Helpers Render the Wrong Value!

    Another one by Rick Strahl:

    ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes

    0 讨论(0)
提交回复
热议问题