加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何从模型中为ASP.NET MVC DropDownList设置默

发布时间:2020-12-16 07:19:50 所属栏目:asp.Net 来源:网络整理
导读:我是mvc的新手.所以我用这种方式填充下拉列表 public ActionResult New(){ var countryQuery = (from c in db.Customers orderby c.Country ascending select c.Country).Distinct(); ListSelectListItem countryList = new ListSelectListItem(); string de
我是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,它将保存您想要在视图中呈现的所有内容.

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使用文件顶部的以下行

@model namespace.MyViewModel

您可以随时使用该模型

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读