ASP.NET MVC MultiSelectList with selected values not selecting properly

后端 未结 6 1155
猫巷女王i
猫巷女王i 2020-12-02 17:09

I know others have asked this question, but I\'m totally confused by this:

This displays the dropdown with no values selected:

<%= Html.DropDownLi         


        
6条回答
  •  天涯浪人
    2020-12-02 17:57

    I had the same problem, I used my own extention method to generate the html and problem solved

        public static MvcHtmlString ListBoxMultiSelectFor(
            this HtmlHelper helper,
            Expression> expression,
            IEnumerable selectList,
            object htmlAttributes)
        {
            return ListBoxMultiSelectFor(helper, expression, selectList, new RouteValueDictionary(htmlAttributes));
        }
    
        public static MvcHtmlString ListBoxMultiSelectFor(
            this HtmlHelper helper,
            Expression> expression,
            IEnumerable selectList,
            IDictionary htmlAttributes)
        {
            string name = ExpressionHelper.GetExpressionText(expression);
    
            TagBuilder selectTag = new TagBuilder("select");
            selectTag.MergeAttributes(htmlAttributes);
            selectTag.MergeAttribute("id", name, true);
            selectTag.MergeAttribute("name", name, true);
            foreach (SelectListItem item in selectList)
            {
                TagBuilder optionTag = new TagBuilder("option");
                optionTag.MergeAttribute("value", item.Value);
                if (item.Selected) optionTag.MergeAttribute("selected", "selected");
                optionTag.InnerHtml = item.Text;
                selectTag.InnerHtml += optionTag.ToString();
            }
    
            return  new MvcHtmlString(selectTag.ToString());
        }
    

提交回复
热议问题