asp.net-mvc - 如何从模型设置 ASP.NET MVC DropDownList 的默认值

标签 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>)

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

最佳答案

那么这不是一个很好的方法来做到这一点。

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

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

在 View 中,使用文件顶部的以下行声明此 View 需要类型为 MyViewModel 的模型
@model namespace.MyViewModel 

您可以随时随意使用模型
@Html.DropDownList("Country", Model.CountryList, Model.Country)

关于asp.net-mvc - 如何从模型设置 ASP.NET MVC DropDownList 的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991387/

相关文章:

asp.net-mvc - 如何更改kendo ui grid mvc中的默认过滤器运算符

asp.net-mvc - 如何使用 PostAsJsonAsync 调用 MVC3 Controller 操作

c# - 如何从 asp.net mvc 3 应用程序中的 App_Data 文件夹中删除文件?

c# - "Collection was modified"尝试枚举包中的文件时出错

c# - 拆分实体数据模型属性的数据注释 [必需] 属性

mysql - 正确将数据写入表(ASP.NET MVC)

jquery - 阻止只读复选框调用事件处理程序?

asp.net-mvc - 多个复选框表单的 ASP.Net MVC6 语法

c# - 更改在Razor MVC中创建区域的方式的最佳方法是什么?

asp.net-mvc - .net MVC处理由ajax加载的 View 编译错误