后台:
/// <summary> /// 生成分類下拉-列表框,選中指定的項 /// </summary> /// <param name="html"></param> /// <param name="selectedValue"></param> /// <returns></returns> public static MvcHtmlString SelectList_Category(this HtmlHelper html, long selectedValue) { Data.IRepository _iRepository = new Data.DataRepository(); StringBuilder sb = new StringBuilder(); sb.Append("<select name='Category' id='Category'>"); foreach (var i in _iRepository.GetModel<Category>()) { if (i.ID == selectedValue && selectedValue != 0) sb.AppendFormat("<option value='{0}' selected='selected'>{1}</option>", i.ID, i.Name); else sb.AppendFormat("<option value='{0}'>{1}</option>", i.ID, i.Name); } sb.Append("</select>"); return MvcHtmlString.Create(sb.ToString()); } /// <summary> /// 生成分類下拉列表框 /// </summary> /// <param name="html"></param> /// <returns></returns> public static MvcHtmlString SelectList_Category(this HtmlHelper html) { return SelectList_Category(html, 0); }
前台調用:
@Html.SelectList_Category()
我們從代碼中可以看到,這個擴展方法其實是對ViewPage頁面類上的HtmlHelper對象進行的擴展,它的對象名稱是Html,所以在繼承了ViewPage或者ViewUserControl的頁面中,都可以使用SelectList_Category這個擴展方法
原文:http://www.cnblogs.com/lori/archive/2012/03/05/2381196.html