【问题标题】:How to set default value for ASP.NET MVC DropDownList from model如何从模型中为 ASP.NET MVC DropDownList 设置默认值
【发布时间】:2014-04-10 14:44:45
【问题描述】:

我是 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>)

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

【问题讨论】:

  • @Html.DropDownList("Country", ViewBag.Country as List, "DefaultValueHere")
  • 你应该使用 Model 而不是 ViewBag。 stackoverflow.com/questions/6807256/…
  • @DanielMelo:实际上,该参数决定了应该为“空”选项显示的名称,不是默认值。
  • @Html... sn-p 判断,ViewBag.Country = countryList; 应为ViewBag.Countries = "UK";

标签: asp.net-mvc


【解决方案1】:

这不是一个好方法。

创建一个 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
}

用你需要的数据填充它。

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);
}

在视图中,使用文件顶部的以下行声明此视图需要一个 MyViewModel 类型的模型

@model namespace.MyViewModel 

您可以随时使用该模型

@Html.DropDownList("Country", Model.CountryList, Model.Country)

【讨论】:

  • 这是什么行 Selected=(item == defaultCountry ? true : false) });默认国家在哪里??它不在代码中。
【解决方案2】:

你不能使用Html.DropDownList设置默认值,如果你想有一个默认值,属性本身应该有一个默认值。

private string country;
public string Country
{
    get { return country ?? "UK"; }
    set { country = value; }
}

然后,当下拉列表呈现时,只要“UK”实际上是其中一个选项的值,它就会自动设置为那个。

【讨论】:

    【解决方案3】:

    如果DropDownList在控制器中填写并通过ViewBag发送到视图,你可以这样做:

    ViewBag.MyName = new SelectList(DbContextname.Tablename, "Field_ID", "Description",idtobepresented); 
    

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 2010-09-23
      • 2017-07-26
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      相关资源
      最近更新 更多