Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Html.HiddenFor(Model => Model.Id) not passing back to Controller

I have created a strongly typed MVC3 Razor view using the scaffolding code.

The model is a POCO with a base type of PersistentEntity which defines a property called Created, Updated and Id.

Id is an int, Created and Updated are DateTime.

I am using Html.HiddenFor to create the hidden field on the view.

@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.Created)
@Html.HiddenFor(model => model.Updated)

On the page, the hidden input is being rendered properly, with the Id being set in the value.

<input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="12">

However when the page is submitted to the controller [HttpPost]Edit(Model model) the Id property is always 0. Created and Updated are correctly populated with the values from the View.

enter image description here

This should be 12 in the case of the example in this post. What is going wrong?


I am aware that I can change the method signature to [HttpPost]Edit(int personID, Person model) as the personID is in the get string, however why does the model not get populated with the hidden field?


Update

The problem was that the setter on PersistentEntity was protected, ASP could not set the property, and swallowed it. Changing this to public has solved the problem.

public abstract class PersistentEntity
{
    public virtual int Id { get; protected set; }
    public virtual DateTime Created { get; set; }
    public virtual DateTime Updated { get; set; }
}
like image 360
Darbio Avatar asked Sep 26 '11 10:09

Darbio


1 Answers

public virtual int Id { get; protected set; }

protected set; <!-- That's your problem. You need a public setter if you want the default model binder to be able to assign the value.

like image 171
Darin Dimitrov Avatar answered Nov 07 '22 03:11

Darin Dimitrov