2011-08-03 133 views
0

我是新來的MVC,如此忍受我交手......MVC3 - 掌握DropDownList的

我有我的新形式\視圖中工作(創建並添加客戶端) 但現在我希望讓用戶如此指定新客戶端所在的國家/地區從下拉列表中刪除。但我很確定我該如何做到這一點?

視圖模型

public class ClientNew 
{ 
    public string Company { get; set; } 
    public string Address { get; set; } 
    //New 
    public IEnumerable<CountryList> Country{ get; set; } 
} 

public class CountryList 
{ 
    public string Id { get; set; } 
    public string Name { get; set; } 
} 

控制器 (這是爲可能是錯誤的,這是做的最好的方法是什麼?)

public ActionResult New() 
{ 
    var cl= new List<CountryList>(); 
    cl.Add(new CountryList(){Id = "abcd",Name = "UK"}); 
    cl.Add(new CountryList() { Id = "abce", Name = "USA" }); 
    var model = new ViewModels.ClientNew(); 
    model.Country= cl; 
    return View("New", model); 
} 

查看(不知道如何在下探此)

Html.DropDownList("Id" ??????) 

回答

1

在你的觀點你會設置你的下拉屬性Id。這是當您發佈到表單時在下拉列表中選擇的當前值。將用於下拉菜單的數據是一個名爲Countries的SelectList,存在於您的模型中。

@Html.DropDownListFor(m => m.Id, Model.Countries) 

您的視圖模型將有你的ID,名稱和國家屬性,還有其他任何你需要的。

public class ClientNewViewModel { 
    public string Id { get; set; } 
    public string Name { get; set; } 

    public SelectList Countries { get; set; } 
} 

在您的控制器中,您需要將模型傳遞給視圖。您將需要填充國家選擇列表。請記住,當您POST和驗證失敗時,您需要填充此值。

public ActionResult New() 
{ 
    var model = new ClientNewViewModel(); 

    model.Countries = new SelectList(service.GetCountries(), 
     "Id", "Name"); // set up what properties are used for id/name of dropdown 

    return View(model); 
} 

[HttpPost] 
public ActionResult New(ClientNewViewModel model) 
{ 
    if(!ModelState.IsValid) 
    { 
     model.Countries = new SelectList(service.GetCountries(), 
      "Id", "Name"); 

     return View(model); 
    } 

    // redirect on success 
    return RedirectToAction("Index"); 
} 
+0

作爲替代方案,你可以有你的視圖模型的IEnumerable 國家,然後就做一個LINQ在Action中進行投影來設置它。國際海事組織這是一個更好的方法,因爲它是可重構的,不依賴於魔術字符串。 –

0
Html.DropDownList("Id", 
        Country.Select(x => new SelectListItem 
              { 
               Text = x.Name, 
               Value = x.Id 
              }));