asp.net mvc中DropDownList

时间:2023-03-10 02:56:59
asp.net mvc中DropDownList

asp.net mvc中DropDownList的使用.

下拉列表框 以分为两个部分组成:下拉列表默认选项

DropDownList扩展方法的各个重载版本基本上都会传递到这个方法上:

 

public static string DropDownList(this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem>selectList,
string optionLabel,
IDictionary<string,object>htmlAttributes)

没有指定selectList时,该方法自动绑定列表,即从ViewData中查找name所对应的值.

如果提供了selectList,将自动绑定默认选项,即从selectList中找Selected=true的SelectedListItem

selectList里面包含

Items:用于在select标记中出现的列表,通常使用option标记表示。IEnumerable类型。

DataTextField:作为option的text项,string类型。

DataValueField:作为option的value项,string类型。

SelectedValues:选中项的value值,IEnumerable类型。

显然,作为DropDownList来说,选中项不可能为IEnumerable,因此SelectList提供了一个新的属性:

SelectedValue:选中项的value值,object类型。

同时,SelectList的构造函数如下所示:

public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)
: base(items, dataValueField, dataTextField, ToEnumerable(selectedValue)) {
SelectedValue = selectedValue;
}

实用例子:

var users=GetUsers();//获取所有用户
var selectList=new SelectList(users,"Age","Name","");
ViewData["list"]=selectList;
@Html.DropDownList("list")

列表:users

显示的选项:"Age"

选项对应的值:"Name"

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

注意:如果以上这种情况,视图使用@Html.DropDownList("list",ViewData["list"] as SelectList)是不会选中默认值的

控制器中用

ViewData["ProvinceId"] = Provinces.Select(o => new SelectListItem

            {

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

                Text = o.ProName,

                Value = o.ProID.ToString()

            });

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

@Html.DropDownList("ProvinceId")

服务端

  1. ViewData["category"] = new SelectList(GetAll(), "ID", "CategoryName");

这个数据源 ID=name是一一对应的关系

前端

@Html.DropDownList("dropdownlistID",ViewData["category"] as SelectList,"请选择") 默认显示是"请选择"
@Html.DropDownList("controlID",ViewData["category"] as SelectList,Model.CategoryName) 默认显示值是Model.CategoryName
@Html.DropDownListFor(o =>o.ID, ViewData["category"] as IEnumerable<SelectListItem>, "请选择", new { id="parentID"})

这个例子,=>o.ParentID就表示,o.ParentID等于数据源中ID的记录将被选中

@Html.DropDownList("priex",(IEnumable(SelectListItem))ViewData["category"],"全部",new{onchange="GetList()"})

View参数说明:1.指定DropDownList的ID

2.指定SelectList

3.可以指定默认值

Controller部分

public ActionResult Add()
{
ViewData["category"] = new SelectList(GetAll(), "ID", "CategoryName");
return View();
}

Html.DropDownListFor的使用

@Html.DropDownListFor(o=>o.ID,
new[]{
new SelectListItem(){Text="河南",Value=""},
new SelectListItem(){Text="河北",Value=""}
},
"请选择一个"
)

前端

 @Html.DropDownListFor(o=>o.ParentID,ViewData["category"] as IEnumerable<SelectListItem>,"请选择")

第一个参数:上级ID

第二个参数:SelectListItem集合

第三个参数:设置默认值

public ActionResult Add()
{
ViewData["category"] = new SelectList(GetAll(), "ID", "CategoryName");
//数据, ID, Value
return View();
} @Html.DropDownList("role", ViewData["role"] as IEnumerable<SelectListItem>)