Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.Hidden field not getting set

Tags:

asp.net-mvc

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!
}
like image 521
chani Avatar asked Dec 09 '22 17:12

chani


1 Answers

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")
like image 82
chani Avatar answered Jan 11 '23 01:01

chani