简体   繁体   中英

mvc drop down list?

IEnumerable<DeliveryRunRecord> deliveries = _deliveryRunService.GetAll();
List<SelectListItem> listOfDeliveryRuns = deliveries.Select(x => new SelectListItem
            {
                Value = x.Id.ToString(),
                Text = x.Name,
                Selected = "Select".ToString()
            }).ToList();

Would like 'Select' to appear before the drop down is selected, but not available when it is clicked, only allowing the user to select the values in deliveries??

I think you need another item for default selection like this:

(This approach requires System.Linq namespace to be included)

SelectListItem defaultItem = new SelectListItem 
{ 
    Selected = true, 
    Text = "Select", 
    Value = "NONE" 
};
List<SelectListItem> listOfDeliveryRuns = deliveries
    .Select(x => new SelectListItem
    {
        Value = x.Id.ToString(),
        Text = x.Name,
        Selected = false
    })
    .ToList()
    .Insert(0, defaultItem);

You probably can do what you are asking for in your .cshtml as well.

@Html.DropDownList("DeliveryId", new SelectList(ViewBag.deliveries as System.Collections.IEnumerable, "Key", "Value"), "--Select--")

The above will display the dropdown list with "--Select--" as the item selected by default. I have just copied a sample which used a Dictionary with your item values and is passed in as a parameter through ViewBag.

Selected Property of SelectListItem is Boolean type so you can not assign string it should be false or true.

But what you want achieve can be simply done on view. @Html.DropDownList("dropdown1", new SelectList(ViewBag.deliveries , "Value", "Text", 0 ), "please select", new { onchange = "form.submit();" })

Pay attention to fourth parameter on DropDownList Method, it's zero .

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM