2011-08-03 136 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 
              }));