Default values for model fields in ASP.Net MVC3
I have a simple Action in my Controller:
public ActionResult Edit(int itemId)
{
return View(new EditModel() { ItemId = itemId + 1 });
}
public class EditModel
{
public int ItemId { get; set; }
public string Title { get; set; }
}
The problem comes in the View, when I try to display everything.
Model.ItemId: @Model.ItemId
@Html.EditorForModel()
Since action parameter and property on EditModel have the sa开发者_如何学编程me name (itemId
) I get the following:
Is this a correct behaviour? How can I change default value displayed inside a form in that case?
This may be somehow confusing for the first look, but yes, this is default(correct) behavior. Controller.ModelState is the privileged supplier for the values when you use EditorFor
or similar editor helpers, over the model itself. But there's trickier point in your situation.
ModelState is populated with action parameters and values that take part in model binding. When you call that action, ModelState
is populated with "ItemId" = action parameter(itemId) value
. Later, EditorFor
sees that is should draw editor for ItemId
. As ModelState has already got ItemId
, it does not look at model value, but extracts it from ModelState["ItemId"]
. Tricky source of your error is that action parameter name matches the model property name and modelState prefers that over model value. The best solution (clean one) would be to just rename action parameter, so that it does not match the model property name.
public ActionResult Edit(int initialItemId)
{
return View(new EditModel() { itemId = initialItemId + 1 });
}
This will do the trick.
You can write
Model.ItemId: @Model.ItemId
@Html.EditorFor(x => x.Title)
Or hide ItemId for edit with metadata
精彩评论