private static IHtmlString BuildListBox(string name, string defaultOption, IEnumerable <SelectListItem> selectList, object selectedValues, int?size, bool allowMultiple, IDictionary <string, object> htmlAttributes) { //var modelState = ModelState[name]; //if (modelState != null) { selectedValues = selectedValues;// ?? ModelState[name].Value; } if (selectedValues != null) { IEnumerable values = (allowMultiple) ? ConvertTo(selectedValues) : new[] { selectedValues.ToString() }; var newSelectList = new List <SelectListItem>(); var selectedValueSet = new HashSet <string>(from object value in values select Convert.ToString(value, CultureInfo.CurrentCulture), StringComparer.OrdinalIgnoreCase); bool previousSelected = false; foreach (var item in selectList) { bool selected = false; // If the user's specified allowed multiple to be false // only pick up the first item that was selected. if (allowMultiple || !previousSelected) { selected = item.Selected || selectedValueSet.Contains(item.Value ?? item.Text); } previousSelected = previousSelected | selected; newSelectList.Add(new SelectListItem(item) { Selected = selected }); } selectList = newSelectList; } var tagBuilder = new TagBuilder("select") { InnerHtml = BuildListOptions(selectList, defaultOption) }; //if (UnobtrusiveJavaScriptEnabled) //{ // // Add validation attributes // var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name); // tagBuilder.MergeAttributes(validationAttributes, replaceExisting: false); //} tagBuilder.GenerateId(name); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("name", name, true); if (size.HasValue) { tagBuilder.MergeAttribute("size", size.ToString(), true); } if (allowMultiple) { tagBuilder.MergeAttribute("multiple", "multiple"); } else if (tagBuilder.Attributes.ContainsKey("multiple")) { tagBuilder.Attributes.Remove("multiple"); } // If there are any errors for a named field, we add the css attribute. //AddErrorClass(tagBuilder, name); return(tagBuilder.ToHtmlString(TagRenderMode.Normal)); }