如何从模型中设置ASP.NET MVC DropDownList的默认值

Tho*_*mas 4 asp.net-mvc

我是mvc的新手.所以我用这种方式填充下拉列表

public ActionResult New()
{
    var countryQuery = (from c in db.Customers
                        orderby c.Country ascending
                        select c.Country).Distinct();
    List<SelectListItem> countryList = new List<SelectListItem>();
    string defaultCountry = "USA";
    foreach(var item in countryQuery)
    {
        countryList.Add(new SelectListItem() {
                        Text = item, 
                        Value = item, 
                        Selected=(item == defaultCountry ? true : false) });
    }
    ViewBag.Country = countryList;
    ViewBag.Country = "UK";
    return View();       
}

@Html.DropDownList("Country", ViewBag.Countries as List<SelectListItem>)
Run Code Online (Sandbox Code Playgroud)

我想知道如何从模型填充下拉列表并设置默认值.任何示例代码都会有很大的帮助.谢谢

Men*_*gis 6

那么这不是一个很好的方法.

创建一个ViewModel,它将保存您想要在视图中呈现的所有内容.

public class MyViewModel{

  public List<SelectListItem> CountryList {get; set}
  public string Country {get; set}

  public MyViewModel(){
      CountryList = new List<SelectListItem>();
      Country = "USA"; //default values go here
}
Run Code Online (Sandbox Code Playgroud)

填写您需要的数据.

public ActionResult New()
{
    var countryQuery = (from c in db.Customers
                        orderby c.Country ascending
                        select c.Country).Distinct();
    MyViewModel myViewModel = new MyViewModel ();

    foreach(var item in countryQuery)
    {
        myViewModel.CountryList.Add(new SelectListItem() {
                        Text = item, 
                        Value = item
                        });
    }
    myViewModel.Country = "UK";



    //Pass it to the view using the `ActionResult`
    return ActionResult( myViewModel);
}
Run Code Online (Sandbox Code Playgroud)

在视图中,声明此视图期望具有MyViewModel类型的Model使用文件顶部的以下行

@model namespace.MyViewModel 
Run Code Online (Sandbox Code Playgroud)

您可以随时使用该模型

@Html.DropDownList("Country", Model.CountryList, Model.Country)
Run Code Online (Sandbox Code Playgroud)