MVC利用MvcHtmlString在后台生成HTML

        /// <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这个扩展方法

原文地址:https://www.cnblogs.com/lgx5/p/5816801.html