2017-05-31 68 views
0

選擇選定值我有一個enum它看起來像在下拉列表中

public enum Department 
{ 
    Admin, 
    HR, 
    Marketing, 
    Sales 
} 

從這個我想在控制器中創建一個下拉列表,我不喜歡它

public SelectList GetDepartmentDropDownList(string departmentName = null) 
{ 
    var departments = Enum.GetValues(typeof(Department)); 
    SelectList ddl = new SelectList(departments); 

    return ddl; 
} 

這工作正常。但正如你所看到的,我可以傳遞選項參數。當下拉值被保存到數據庫並且用戶回來編輯該部分時,將傳入此可選參數。我試圖實現的是用戶最初選擇的任何內容,當他們回到編輯屏幕時,選擇特定項目,即,如果他們選擇HR,則他們應該選擇HR

如果我做new SelectList(departments, departmentName, departmentName);我得到以下錯誤:

DataBinding: Enums.Department' does not contain a property with the name 'HR'

有人建議如何實現這一目標吧。

在我使用的Html.DropDownListFor()使視圖

@Html.DropDownListFor(m => m.Department, Model.DepartmentDdl, "Please select a Department", new { @class = "form-control", @required = "required" }) 

在我的模型的屬性是

public IEnumerable<SelectListItem> DepartmentDdl { get; set; } 

和Controller創建動作我做

model.DepartmentDdl = GetDepartmentDropDownList(); 

而且在控制器編輯動作中,我做了

model.DepartmentDdl = GetDepartmentDropDownList(departmentName); //department name here is read from the db 
+0

它的綁定的屬性值決定了選擇的內容。顯示你的視圖和你綁定的屬性(你需要將它設置在模型中,然後傳遞給視圖) –

+0

只需在GET方法中將'Department'的值設置爲'Department.HR',它將會選中(在'GetDepartmentDropDownList()'方法中你的參數沒有意義) –

+0

可能重複[SO答案](https://stackoverflow.com/questions/21878673/html-enumdropdowndownlistfor-showing-a-default-text) ? –

回答

1

模型綁定通過綁定到您的屬性的值工作。你需要你通過模型視圖之前設置的屬性Department值在GET方法,例如

var model = new YourModel 
{ 
    Department = Department.HR, 
    DepartmentDdl = GetDepartmentDropDownList() 
}; 
return View(model); 

注意,沒有必要在GetDepartmentDropDownList()方法的參數。在內部,DropDownListFor()方法建立一個新的IEnumerable<SelectListItem>並根據您綁定到的屬性(即將其設置在SelectList的構造函數中將被忽略)設置每個SelectListItemSelected值。