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;    
<%=Html.DropDownList("list")%>

mvc3里面的表示:

控制器代碼:

List<A_MuData> categories = base.CustomerInfo.GetModel() as List<A_MuData>;
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;
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> )

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM