ASP.NET MVC: Hidden field value does not get rendered using HtmlHelper.Hidden

Veli Gebrev picture Veli Gebrev · Jan 7, 2010 · Viewed 69.2k times · Source

Something pretty weird is happening with my app:

I have the following property in my ViewModel:

public int? StakeholderId { get; set; }

It gets rendered in a partial view as follows:

<%= Html.Hidden("StakeholderId", Model.StakeholderId) %>

The form is submitted, and the relevant controller action generates an id and updates the model, before returning the same view with the updated model

The problem I'm experiencing is that the hidden field does not have anything in its "value" attribute rendered the second time even though StakeholderId now has a value.

If I just output the value on its own, it shows up on the page, so I've got it to render the value by doing this:

<input type="hidden" id="StakeholderId" name="stakeholderId" value="<%: Model.StakeholderId %>" />

But it's pretty strange that the helper doesn't pick up the updated value?

(I'm using jQuery to submit forms and render the action results into divs, but I've checked and the html I get back is already wrong before jQuery does anything with it, so I don't think that has much to do with anything)

UPDATE

I've since discovered that I can also clear the relevant ModelState key before my controller action returns the partial view.

Answer

Darin Dimitrov picture Darin Dimitrov · Jan 7, 2010

The helper will first look for POSTed values and use them. As you are posting the form it will pick up the old value of the ID. Your workaround is correct.