简体   繁体   中英

Value of hidden field not correct

I have a hidden field in one of my MVC views

@Html.HiddenFor(model => model.PolicyHolderId, 
    new Dictionary<string, object>{{ "id", "policyHolderIdHidden"}})

When I debug, I can see that the value of this field is set to 1, but when I do the following

$(document).ready(function () {
    alert($("#policyHolderIdHidden").val());
});

the value is displayed as 0. The values for all other hidden fields seem to work 100%. Any idea why this would be happening?

Ok, I'm still not sure why this is happening but found a workaround, probably not the most elegant but it will work if you do not need the values of your model to change as you change the value of the hidden field. I'm not posting the model back to my controller so this solution was sufficient for me

I changed the hidden field code from

@Html.HiddenFor(model => model.PolicyHolderId, 
new Dictionary<string, object>{{ "id", "policyHolderIdHidden"}})

to

@Html.Hidden("policyHolderIdHidden", 
Model.PolicyHolderId, new Dictionary<string, object>{{ "id", "policyHolderIdHidden"}})

I created a model with the property PolicyHolderId and passed it to a view.

Then I copied and pasted your code and it works perfectly, perhaps there is something else in your view conflicting?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM