I think you have three four options. First, when you create your SelectList or enumerate SelectItemList, add the selection using the label and the default value. The room at the top will make it the default if any other value is not already selected in the model. Secondly, you can create a “selection” (and parameters) “manually” in the view, using a loop to create the parameters. Again, adding your default selection if it is not specified in the model. Third, use the DropDownList extension, but change the value of the first parameter using javascript after the page loads.
You cannot use the DropDownList extension to assign the value of the Label option because it is hardcoded to use string.Empty . Below is the corresponding 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, it is best for your model to accept Nullable and mark it as required with RequiredAttribute. I would recommend using a presentation model, rather than an entity model for the presentation. Since the value is Nullable, an empty string will work fine if sent back without selecting a value. Setting it as the required value will lead to a failure of the model verification with the corresponding message that this 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" )
tvanfosson
source share