2016-07-22 87 views
0

我想知道將MVC中的查看值列表傳遞給MVC的一般方法。目前我有2分貝表,我使用db第一個EF6接口。我的主表有一個查找表,我想用查找的所有值填充我的視圖的下拉列表,以便用戶可以在創建和編輯時進行選擇。將查詢值傳遞給下拉列表的最佳方式

EMPLOYEE表

id primary key 
name varchar 
department id - this is the id of the department in the lookup 

Department表

id primary key 
name varchar 

是它最好創建一個局部類員工模型,並添加新的屬性稱爲allDepartments,然後在我的控制器調用一個方法在將模型傳遞給視圖之前獲取所有分區,或者在viewbag/viewdata字典中轉儲部門更好。

這裏的一般方法是什麼?

+0

不創建一個 '局部'類。你創建一個視圖模型 - [什麼是MVC中的ViewModel?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc)。而對於典型的iplementation,請參考[這個問題/答案](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system- int32-but-must-o-o) –

回答

0

你需要創建一個ViewModel這樣的:

public class EmployeeViewModel 
{ 
    public string Name { get; set; } 
    [Required(ErrorMessage = "...")] // to protect against under-posting attacks 
    [Display(Name = "Department")] 
    public int? DepartmentId { get; set; } 
    public IEnumerable<SelectListItem> Departments { get; set; } 
} 

控制器:

public ActionResult Create() 
{ 
    var employeeViewModel = new EmployeeViewModel(); 
    employeeViewModel.Departments = GetDepartments().Select(option => new SelectListItem 
    { 
     Text = option.name, 
     Value = option.Id.ToString() 
    }); 
    return View(employeeViewModel); 
} 

// Post 
public ActionResult Create(EmployeeViewModel model) 
{ 
    // Map ViewModel to Entity and Save to db... 
} 

查看:

@model EmployeViewModel 

<div class="form-group"> 
    @Html.LabelFor(model => model.Name) 
    @Html.TextBoxFor(model => model.Name, new { @class = "form-control" }) 
    @Html.ValidationMessageFor(model => model.Name) 
</div> 

<div class="form-group"> 
    @Html.LabelFor(model => model.DepartmentId) 
    @Html.DropDownListFor(model => model.DepartmentId, Model.Departments, "Choose...") 
    @Html.ValidationMessageFor(model => model.DepartmentId) 
</div> 
+0

人們需要學習指出投票的理由,而不是僅僅去做它... –

+0

不,他們不這樣做。你的回答是確定的,不值得讚賞,但它包含一些不好的做法(和錯字,所以它不會工作)。屬性'Departments'應該是'IEnumerable ',並且在控制器中構建'SelectList',而不是視圖(視圖變爲'@ Html.DropDownListFor(m => m.DepartmentId,Model.Departments,「Choose ...')屬性'DepartmentId'應該是'int?'(可爲空),並且必須有'[Required]'屬性 –

+0

並且設置'SelectListItem'的'Selected'屬性是沒有意義的 - 它被DropDownListFor )'方法(在內部,方法建立一個新的'SelectList',並根據你綁定的屬性的值設置'Selected'屬性,如果你改正了這個問題,我會很樂意給你一個upvote。 –

相關問題