Saturday, March 9, 2013

NEVER use HTML Helpers for Hidden fields (Asp.Net MVC)

 This is the second time around when I ran into this problem - Hidden fields on a view after rendering it back from the controller after POST, does not update the hidden fields with latest values. The reason, I found online is that the view rendering engine (Razor, in this case) first looks at the values being posted for the Helper fields and uses them rather than the ones, that were returned from the controller after the POST. What is the reason behind this design - I dont know. 

Example:
So, if you have a view like this - 


<div class="span9">
        @using (Html.BeginForm("Payment""Entity"FormMethod.Post))
        { 
            @Html.ValidationSummary("Please provide the required fields")
            @Html.HiddenFor(m => m.EntityId)
            .....


Instead do: 

 <div class="span9">
        @using (Html.BeginForm("Payment""Entity"FormMethod.Post))
        { 
            @Html.ValidationSummary("Please provide the required fields")
            <input type="hidden" name="EntityId" id="EntityId" value="@Model.EntityId" />


Hope you save some time. 

6 comments:

Unknown said...

Excellent ..i have been irritating with this type of behavior of hidden field .I did more R&D but your solution is excellent very excellent
You solved all the issues with one solution since we have demo after two days it is blocker now so thanks a lot

Unknown said...

Thank you. I am glad it helped you.

Unknown said...

Or, You can write ModelState.Clear() before Your return in "Payment" Action. It resolved issue for me.

Unknown said...

Thanks a ZILLION Shivagaadu

Daniel Tilly said...

Sasha Dzhurko - this is the correct answer. The model probably has errors in it.

Unknown said...
This comment has been removed by the author.