How do I set a value for the default option with Html.DropDownList

后端 未结 4 1065
眼角桃花
眼角桃花 2020-12-20 20:20

I\'m using ASP MVC RC1.

A form I\'m using contains a dropdownlist which I have put in a view with this code.

<%= Html.DropDownList(\"areaid\", (Se         


        
4条回答
  •  臣服心动
    2020-12-20 21:00

    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 Areas { get; set; }
        ...
    }
    
    @Html.DropDownListFor( model => model.AreaId, Model.Areas, "Select Area Id" )
    

提交回复
热议问题