天天看點

MVC RC2中關于HtmlHelper給DropDownList設定初始選中值的問題

Asp.Net MVC RC2中Helper提供的DropDownList好象并不太好用,特别想給下拉框設定初始選中值的時候(可能我還沒找到正确的方法)

小試了一下,有二個簡單的解決辦法:

1.回到最原始的asp的辦法,直接在view的循環中判斷,具體代碼就不寫了,有過Asp/Php經驗的一點就明白

2.自己再寫一個DropDownList的重載版本,如下:

MVC RC2中關于HtmlHelper給DropDownList設定初始選中值的問題
MVC RC2中關于HtmlHelper給DropDownList設定初始選中值的問題

Code

/// <summary>

        /// 生成下拉清單

        /// </summary>

        /// <param name="helper"></param>

        /// <param name="SelectListName">下拉清單的Name值</param>

        /// <param name="SelectItems">資料源</param>

        /// <param name="SelectedValue">選中值</param>

        /// <param name="Attributes">附加屬性值,比如onchange="

MVC RC2中關于HtmlHelper給DropDownList設定初始選中值的問題

"之類</param>

        /// <returns></returns>

        public static string DropDownList(this HtmlHelper helper, string SelectListName, IEnumerable<SelectListItem> SelectItems, string SelectedValue, string Attributes)

        {

            StringBuilder sb = new StringBuilder();

            sb.Append("<select");

            if (SelectListName.Trim() != "")

            {

                sb.Append(" name=\"" + SelectListName + "\"");

            }

            else

                return "";

            if (Attributes.Trim() != "")

                sb.Append(" " + Attributes.Trim());

            sb.Append(">");

            foreach (SelectListItem item in SelectItems)

                if (item.Value == SelectedValue)

                {

                    sb.Append("<option value=\"" + item.Value + "\" selected=\"selected\">" + item.Text + "</option>");

                }

                else

                    sb.Append("<option value=\"" + item.Value + "\">" + item.Text + "</option>");

            sb.Append("</select>");

            return sb.ToString();

        }

調用代碼如下:

Action部分:

List<SelectListItem> _items = new List<SelectListItem>();

MVC RC2中關于HtmlHelper給DropDownList設定初始選中值的問題

ViewData["Citys"] = _items;

View部分:

<%=Html.DropDownList("SelName",  (IEnumerable<SelectListItem>)ViewData["Citys"],item.CityId.ToString(),"onchange=\"alert('Test')\"") %>