I have a hidden field in my view like this:
using (Html.BeginForm("Action", "Schedule"))
{
@Html.Hidden("Id", Model.Schedule.Id)
...
}
And an action method that takes in the information like this:
public ActionResult AddEventToSchedule(Event NewEvent, Guid Id)
{
// Do something
}
I keep getting an empty Guid passed in, even when Model.Schedule.Id is not empty. I checked the html source and the hidden field is an empty Guid as well (used a breakpoint to verify that Model.Schedule.Id is not empty).
The strange thing is when I tried to access the Id value through the model like below, the html hidden field was populated correctly with the guid, but the model passed into the action method was empty.
public ActionResult AddEventToSchedule(Event NewEvent, ScheduleModel model)
{
// model.Schedule is null!
}
Figured this out with the help of this question: MVC3 Model Binding - List to Hidden fields
Apparently HTML helpers check ModelState for a value before they check Model. The reason why I only saw this behavior when I added the Id as a parameter to the action method was that this invoked the model binder to populate ModelState with the Id. And the reason why the Id was always an empty Guid was because that's the value the first time the action method is called.
I added this line to my action method and everything works fine now:
ModelState.Remove("Id")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With