2012-08-05 55 views
1

我是新來的MVC3,並試圖學習一些東西。使用Razor視圖引擎。 mysql數據庫。我有一張桌子,我保留公司(公司ID,公司名稱等)。我有相同的屬性模型:mvc3 dropdownlist binding

public class CompanyModel{ 
    public int companyID; 
    public string companyName; 
    ...... 
    .... 
} 

我想創建持有的公司一個下拉列表,顯示我的公司名稱,當我選擇一個項目,我需要能夠訪問companyID。我可以查詢該表,並在公司名單中的所有行:

List<Company> companies = new List<Company>(); 
companies = getCompanies(); 

,但我不知道如何將此列表下拉列表綁定以及如何從POST方法的調用之後獲得所選擇的值我的控制器。

任何幫助,將不勝感激。

+0

http://stackoverflow.com/questions/7247871/bind ing-to-a-dropdownlist-in-mvc3?rq = 1 – 2012-08-05 16:27:05

回答

2

你可以使用一個視圖模型:

public class MyViewModel 
{ 
    [DisplayName("Company")] 
    public int CompanyId { get; set; } 
    public IEnumerable<SelectListItem> Companies { get; set; } 
} 

,然後讓你的控制器動作實例化,填充和通過這個視圖模型到視圖:

public class CompaniesController: Controller 
{ 
    public ActionResult Index() 
    { 
     List<Company> companies = getCompanies(); 

     var model = new MyViewModel(); 
     model.Companies = companies.Select(x => new SelectListItem 
     { 
      Value = x.companyID.ToString(), 
      Text = x.companyName 
     }); 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     // model.CompanyId will contain the selected value here 

     return Content(
      string.Format("You have selected company id: {0}", model.CompanyId) 
     ); 
    } 
} 

最後一個強類型的視圖您可以呈現包含下拉列表的HTML表單:

@model MyViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(x => x.CompanyId) 
    @Html.DropDownListFor(x => x.CompanyId, Model.Companies) 
    <button type="submit">OK</button> 
} 
+0

非常感謝你:)它工作得很好;) – 2012-08-05 17:12:47