Reputation: 2691
I'm working on a ASP.NET MVC3 project where I've defined the following model:
public class Model{
[Key]
int Id { get; set; }
int MappedId { get; set; }
}
This model is passed from a Controller to a Razor view, as follows:
public class Controller:Controller{
public ActionResult Edit(int id) {
Model model = repository.Get(id);
return View(model);
}
}
The model properties are rendered in the view:
@using(Html.BeginForm()) {
@Html.HiddenFor(model => model.Id);
@Html.HiddenFor(model => model.MappedId)
}
What's strange is that the both the hidden inputs get the same value, even though the model properties have different values when passed to the View. E.g. if the Model.Id has value 0 and Model.MappedChannelId have value 7, both hidden inputs are set to the same value 7:
<input id="Id" class="valid" type="hidden" value="7" name="Id" data-val-required="The Id field is required." data-val-number="The field Id must be a number." data-val="true">
<input id="MappedId" class="valid" type="hidden" value="7" name="MappedId" data-val-required="The MappedId field is required." data-val-number="The field MappedId must be a number." data-val="true">
Does anyone have an idea about why Html.HiddenFor(model=> model.Id) set the value to the same value as model.MappedId, even if model.Id has a different value when passed to the View?
Upvotes: 2
Views: 2086
Reputation: 38468
My guess is you get the MappedId value from the id parameter of your action. Then you set the Id property with some other value. However in your view you still have Id value from the action parameter and default model binder uses that value for binding Id property. It basically ignores the value from the model instance.
You can solve it by changing the name of Id property in your model. If you don't want that, you should change the name of the action parameter. However you need to create a custom route for it if you don't want to pass its value by querystring.
Upvotes: 2