I think you have three four options. First when you are building your SelectList or enumerable of SelectItemList, prepend the selection with your option label and default value. Putting it at the top will make it the default if some other value isn't already chosen in the model. Second, you could build the select (and options) "by hand" in the view using a loop to create the options. Again, prepending your default selection if one isn't supplied in the model. Third, use the DropDownList extension, but modify the value of the first option using javascript after the page is loaded.
It doesn't seem to be possible to use the DropDownList extension to assign a value to an optionLabel as it is hard-coded to use string.Empty
. Below is the relevant code snippet from http://www.codeplex.com/aspnet.
// Make optionLabel the first item that gets rendered.
if (optionLabel != null) {
listItemBuilder.AppendLine(ListItemToOption(new SelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false }));
}
EDIT: Finally, the best way is to have your model take a Nullable value and mark it as required using the RequiredAttribute. I would recommend using a view-specific model rather than an entity model for the view. Since the value is Nullable, the empty string will work fine if posted back without choosing a value. Setting it as a required value will cause the model validation to fail with an appropriate message that the value is required. This will allow you to use the DropdownList helper as is.
public AreaViewModel
{
[Required]
public int? AreaId { get; set; }
public IEnumerable<SelectListItem> Areas { get; set; }
...
}
@Html.DropDownListFor( model => model.AreaId, Model.Areas, "Select Area Id" )
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…