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.
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 str开发者_开发问答ing, 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; }
}
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.
精彩评论