2017-07-30 115 views
1

我有問題試圖讓預選值工作。 我試過在SelectListItem中包含Selected,但它不會預先選擇。 任何線索,爲什麼它不匹配?謝謝你的幫助。DropDownListFor未選擇默認

RetailerId是int。 (它不是定義爲枚舉)

零售商是一個枚舉,例如:

public enum Retailer 
{ 
    Sears = 10, 
    Macys = 20 
} 

這裏是查看代碼:

@Html.DropDownListFor(x => x.RetailerId, 
        Enum.GetValues(typeof(Retailer)).Cast<Retailer>() 
        .OrderBy(o => o.GetDescription()) 
        .Select(o => new SelectListItem() { Text = o.GetDescription(), Value = o.ToString(), Selected = (o.ToInt() == Model.RetailerId) }), 
        new { @data_placeholder = "Select Retailer", @class = "form-control" }) 

回答

3

你產生的SelectListItem一個集合,其中所述Value是要麼不能綁定到RetailerId這是int的「Sears」或「Macys」。

請注意,當綁定到模型屬性時,SelectListItemSelected屬性將被忽略。該方法在內部根據您綁定的屬性的值設置Selected屬性,並且由於其值爲int,它不匹配任何選項值,因爲必須是第一個選項。

您可以通過修改.Select條款,使這項工作,以

.Select(o => new SelectListItem() { Text = o.GetDescription(), Value = ((int)o).ToString() }), 

另外,模型屬性

public Retailer RetailerId { get; set; } 

改變的.Select子句

.Select(o => new SelectListItem() { Text = o.GetDescription(), Value = o.ToString() }), 
+0

感謝你這麼很多,它的工作原理! thx的解釋!本來希望在裝訂時知道選定的財產在某些文件中是無用的。 – user1161137