微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐