新文章 网摘 文章 随笔 日记

MVC自动填充下拉列表

MVC自动填充下拉列表:

添加DropDownAttribute属性:

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
    public class DropDownAttribute : UIHintAttribute
    {
        public DropDownAttribute(string templateName)
            : base(templateName)
        {
        }
    }


App_Code中加入:

using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;


namespace System.Web.Mvc.Html
{
    public static class HtmlExtensions
    {
        public static IEnumerable<SelectListItem> SetSelected(this IEnumerable<SelectListItem> selectList, object selectedValue)
        {
            selectList = selectList ?? new List<SelectListItem>();

            if (selectedValue == null)
                return selectList;

            var value = "";
            var valueType = selectedValue.GetType();
            if (valueType.IsEnum)
            {
                value = ((int)selectedValue).ToString();
            }
            else
            {
                value = selectedValue.ToString();
            }

            return selectList
                .Select(m => new SelectListItem
                {
                    Selected = string.Equals(value, m.Value),
                    Text = m.Text,
                    Value = m.Value
                });
        }


        public static IEnumerable<SelectListItem> GetAutomatedList<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            return ((IEnumerable<SelectListItem>)htmlHelper.ViewData["DDKey_" + metadata.PropertyName]);
        }


        public static MvcHtmlString ThFor(string text, string @class, string style)
        {
            return new MvcHtmlString($"<td class=\"{@class}\" style=\"{style}\">{text}</td>");
        }
    }
}


View->Shared-> EditorTemplates中加入DropDown.cshtml:

@model object
@Html.DropDownListFor(m => m, Html.GetAutomatedList(m => m).SetSelected(Model), htmlAttributes: new { @class = "form-control" })



Model中要显示下拉列表的字段加入下面的属性:

 [DropDown("DropDown")]


Controller中准备数据:

        /// <summary>
        /// 准备客户端ID
        /// </summary>
        /// <returns></returns>
        protected List<SelectListItem> PrepareClientIds()
        {
            var clientService = MvcApplication.Container.ResolveOptional<IClientsService>();
            List<SelectListItem> clientIds= clientService.GetAll()
                    .Select(r => new SelectListItem { Text =r.ClientName, Value = r.Id.ToString() })
                    .ToList();

            clientIds.Insert(0, new SelectListItem { Text = "------", Value = "" });
            ViewData["DDKey_Client_Id"] = clientIds;
            return clientIds;
        }

 



View中正常绑定Id即可:

@Html.EditorFor(r=>r.Client_Id)

 



posted @ 2020-07-15 13:35  岭南春  阅读(83)  评论(0)    收藏  举报