MVC中如何使用DropDownList

方式一


var users=GetUsers();//获取所有用户
var selectList=new SelectList(users,"Age","Name","24");
ViewBag.list=selectList;

//cshtml使用
@Html.DropDownList("list")

//说明

列表:users

显示的选项:"Age"

选项对应的值:"Name"

默认选中的项为 值为"24"的记录

方式二


//控制器中用:

 ViewBag.ProvinceId = Provinces.Select(o => new SelectListItem

            {

                Selected = o.ProName == "河南省" ? true : false,

                Text = o.ProName,

                Value = o.ProID.ToString()

            });




//前端用:这样配合就会有默认值

@Html.DropDownList("ProvinceId")

方式三


List items = new List();
items.Add(new SelectListItem { Text = "Kirin", Value = "29" });
items.Add(new SelectListItem { Text = "Jade", Value = "28", Selected = true});
items.Add(new SelectListItem { Text = "Yao", Value = "24"});
ViewBag.list = items;

//在View中使用

@Html.DropDownList("list")

方式四


List items = new List();
items.Add(new SelectListItem { Text = "Kirin", Value = "29" });
items.Add(new SelectListItem { Text = "Jade", Value = "28"});
items.Add(new SelectListItem { Text = "Yao", Value = "24"});
ViewBag.list = items;
ViewBag.selected = 24;

//View中使用

@Html.DropDownList("selected", ViewBag.list as IEnumerable)

//说明

将ViewBag.list绑定为下拉框,然后从ViewBag获取key为selected的项,并将下list中Value值与该项的值相等的SelecteListItem设为默认选中项。

方式五


public enum Unit
{
  吨,
  堆,
  捆
}
var values = Enum.GetValues(typeof(Unit)).Cast();
var items = from value in values
           select new SelectListItem { Text = value.ToString(), Value = value.ToString()., Selected = value == Unit.堆 };

//view中使用

@Html.DropDownList("MovieType")

参考资料:MVC中使用DropDownList http://www.studyofnet.com/news/906.html

你可能感兴趣的:(ASP.NET)