MVC中 DropDownList编辑默认选中的使用

MVC DropDownList编辑默认选中

 

DropDownList则与TextBox等控件不同,它使用的是select标记。它需要两个值:在下拉框中显示的列表,和默认选项。而自动绑定一次只能绑定一个属性,因此你需要根据需要选择是绑定列表,还是默认选项。

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。(具体参见HtmlHelper方 法的SelectInternal辅助方法)

例1:如果在Action方法中有如下代码:

List<SelectListItem> items = new List<SelectListItem>();    
    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"});    
    this.ViewData["list"] = items;   

 

在View中这样使用:

<%=Html.DropDownList("list")%>那么辅助方法将率先从ViewData中获取key为list的项,如果该项为IEnumerable类型则绑定到下拉框中,否则将抛出InvalidOperationException。由于第二个SelectListItem的Selected为true,则默认选中第二个。

例2:如果Action中代码如下:

?
List<SelectListItem> items = new List<SelectListItem>();   
    items.Add( new SelectListItem { Text = "Kirin" , Value = "29" });   
    items.Add( new SelectListItem { Text = "Jade" , Value = "28" });   
    items.Add( new SelectListItem { Text = "Yao" , Value = "24" });   
    this .ViewData[ "list" ] = items;   
    this .ViewData[ "selected" ] = 24;  
     
    <%=Html.DropDownList( "selected" , ViewData[ "list" ] as IEnumerable<selectlistitem>)%> </selectlistitem> 

 

那么辅助方法将ViewData["list"]绑定为下拉框,然后从ViewData中获取key为selected的项,并将下list中Value值与该项的值相等的SelecteListItem设为默认选中项。

以上两种方法尽管可以实现DropDownList的正确显示,但并非最佳实践。在实际项目中,我们更希望在代码中使用强类型。例如上面两例 中,SelectListItem的Text和Value本来是User对象的Name和Age属性,然而上面的代码却丝毫体现不出这种对应关系。如果 User列表是从数据库或其他外部资源中获得的,我们难道要用这样的方式来绑定吗?

var users = GetUsers();    
foreach (var user in users)    
{    
    items.Add(new SelectListItem { Text = user.Name, Value = user.Age.ToString() });    
} 

 

这显然是我们所无法容忍的。那么什么是最佳实践呢?

ASP.NET MVC为DropDownList和ListBox(都在html中使用select标记)准备了一个辅助类型:SelectList。SelectList继承自MultiSelectList,而后者实现了IEnumerable。也就是说,SelectList可以直接作为Html.DropDownList方法的第二个参数。

MultiSelectList包含四个属性,分别为:

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" , "24" );   
this .ViewData[ "list" ] = selectList;    <br> <%=Html.DropDownList( "list" )%>  

mvc3里面的表示:

控制器代码:

?
List<A_MuData> categories = base .CustomerInfo.GetModel() as List<A_MuData>;<br>List<A_MuData> DefaultSelect = base .CustomerInfo.GetModel(ObID) as List<A_MuData>;
var selectList = new SelectList(categories, "EqManufacturers" , "EqManufacturers" , DefaultSelect[0]);
ViewData[ "A_MuData_type" ] = selectList;<br>un.dt = base .CustomerInfo.SelectModel(ObID);
return View(un);
视图代码:
 @Html.DropDownList("un.categories", ViewData["A_MuData_type"] as SelectList)

 

当然,你也可以使用不带selectedValue参数的构造函数重载,而在view中显式指定IEnumerable,并在ViewData或view model中指定其他与DropDownList同名的项作为默认选项。

最后让我们来回顾一下DropDownList的三种用法:

建立IEnumerable并在其中指定默认选中项。

建立IEnumerable,在单独的ViewData项或view model的属性中指定默认选中项。

使用SelectList。

附带案例:

?
public static List<SelectListItem> GetDistrictList( string Rid)
       {
           List<XueDa.Model.District> list = XueDa.Caching.DistrictCache.GetCacheDistrictList();
           List<SelectListItem> selectlistDistrict = new List<SelectListItem>();
           foreach (XueDa.Model.District item in list)
           {
               if (Rid == item.Rid.ToString())
               {
                   selectlistDistrict.Add( new SelectListItem()
                   {
                       Text = item.DistrictName,
                       Value = item.Rid.ToString(),
                       Selected = true
                   });
               }
               else
               {
                   selectlistDistrict.Add( new SelectListItem()
                   {
                       Text = item.DistrictName,
                       Value = item.Rid.ToString()
                   });
               }
           }
           selectlistDistrict.Insert(0, new SelectListItem()
           {
               Text = "请选择" ,
               Value = "0" ,
               Selected = true
           });
           return selectlistDistrict;
       }
       @Html.DropDownList( "ID" , new List<SelectListItem>( new List<SelectListItem>() { new SelectListItem() { Text = "请选择" , Value = "0" } }), new { style = "width: 140px" })

上面那个是绑定数据库字段 编辑默认选中 ,有时候是我们自己创建 的不数据库的数据 的案例:

?
public ActionResult EditCustomer( string name)
     {
         string select = string .Empty;
         int etid = int .Parse(EditID);
         A_CustomerInfoModel model = new A_CustomerInfoModel();
         List<A_CustomerInfoModel> list = base .CustomerInfo.GetModelEdit(EditID) as List<A_CustomerInfoModel>;
         if (list.Count > 0)
         {
             foreach (A_CustomerInfoModel item in list)
             {
                 #region 绑定droplist
                 List<SelectListItem> items = new List<SelectListItem>();
                 items.Add( new SelectListItem { Text = "Personal" , Value = "0" });
                 items.Add( new SelectListItem { Text = "Company" , Value = "1" });
                 foreach (SelectListItem item_sp in items)
                 {
                     if (item_sp.Value == item.A_CutomerType)
                     {
                        this .ViewData[ "selected" ]=item.A_CutomerType;                          
                     }
                 }
                 this .ViewData[ "list" ] = items;
                 #endregion
 
                 model.A_Customer_Name = item.A_Customer_Name;
                 model.Homepage = item.Homepage;
                 model.A_province = item.A_province;
                 model.A_city = item.A_city;
                 model.A_Customer_Address = item.A_Customer_Address;
                 model.A_Customer_Post = item.A_Customer_Post;
                 model.A_Contactperson = item.A_Contactperson;
                 model.A_Contacter_Tel = item.A_Contacter_Tel;
                 model.A_IDcardNo = item.A_IDcardNo;
                 model.A_Contacter_fax = item.A_Contacter_fax;
                 model.A_Contacter_email = item.A_Contacter_email;
             }
             return View(model);
         }
         else
         {
             //没有数据
             return View();
         }         
     }

视图:@Html.DropDownList("selected", ViewData["list"] as IEnumerable<SelectListItem> )

转载于:https://www.cnblogs.com/pancong/p/3323852.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值