1

I have a custom AjaxHelper that renders an ajax-enabled dropdownlist. Code below. The helper works well, but it doesn't get the input-validation-error class added to it when validation fails, so it isn't highlighted with the other form elements in the way that I want. In an Html helper I could merge in the attributes given by the HtmlHelper.GetUnobtrusiveValidationAttributes(). But how do I do this in an AjaxHelper?

    public static MvcHtmlString DropDownList(this AjaxHelper ajaxHelper, string name,
        IEnumerable<SelectListItem> list, string optionLabel,
        AjaxOptions ajaxOptions, object htmlAttributes)
    {
        var tag = new TagBuilder("select");
        StringBuilder options = new StringBuilder();
        tag.MergeAttribute("name", name);
        tag.MergeAttribute("id", name);
        TagBuilder option;

        if (optionLabel != null)
        {
            option = new TagBuilder("option");
            option.MergeAttribute("value", string.Empty);
            option.SetInnerText(optionLabel);
            options.Append(option.ToString());
        }

        foreach (SelectListItem item in list)
        {
            option = new TagBuilder("option");
            option.MergeAttribute("value", item.Value);
            if (item.Selected)
            {
                option.MergeAttribute("selected", "selected");
            }
            option.SetInnerText(item.Text);
            options.Append(option.ToString());
        }
        tag.InnerHtml = options.ToString();

        tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        tag.MergeAttributes((ajaxOptions ?? new AjaxOptions()).ToUnobtrusiveHtmlAttributes());
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
Paul Taylor
  • 5,651
  • 5
  • 44
  • 68

0 Answers0