簡體   English   中英

MVC下拉列表?

[英]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();

是否希望在選擇下拉菜單之前出現“選擇”,但單擊時不可用,僅允許用戶選擇交貨中的值?

我認為您需要另一個項目來進行默認選擇,如下所示:

(此方法要求包含System.Linq命名空間)

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);

您可能也可以在.cshtml中執行您想要的操作。

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

上面將顯示下拉列表,默認情況下選擇的項目為“ --Select--”。 我剛剛復制了一個示例,該示例將Dictionary與您的項目值一起使用,並通過ViewBag作為參數傳遞。

SelectListItem的Selected Properties是布爾類型,因此您不能分配字符串,它應該為false或true。

但是您想要實現的目標可以簡單地在視圖上完成。 @ Html.DropDownList(“ dropdown1”,新的SelectList(ViewBag.deliveries,“ Value”,“文本”, 0 ),“請選擇”,新的{onchange =“ form.submit();”})

注意DropDownList方法的第四個參數,它是

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM