1

I'm creating a custom Dropdownlist in C# that will look nicer. I'm writing out a "ul" with each item as an "li" and having jQuery detect the click and update the actual select, which I render with a class that hides it. I don't know what I'm doing wrong, obviously. The custom control inherits from DropDownList

C# Render Method

    protected override void Render(HtmlTextWriter writer)
    {            
        EnsureChildControls();

        writer.WriteLine("<div class='fs_dropdownlist'>");

        writer.WriteLine("<label>" + this.SelectedItem.Text + "</label>");

        writer.WriteLine("<ul>");
        foreach (ListItem item in this.Items)
        {
            if (item.Selected)
                writer.WriteLine("<li class='selected'>" + item.Text + "</li>");
            else
                writer.WriteLine("<li>" + item.Text + "</li>");
        }
        writer.WriteLine("</ul>");

        writer.WriteLine("<div class='hidden'>");
        base.Render(writer);
        writer.WriteLine("</div>");

        writer.WriteLine("</div>");
    }

jQuery click function

$(".fs_dropdownlist li").on("click", function () {
    $(this).addClass("selected");
    var selectedText = $(this).text();
    var div = $(this).closest(".fs_dropdownlist");
    var ddl = div.find("select");        
    var lbl = div.find("label");

    lbl.text(selectedText);
    ddl.val(selectedText); /* Try to set the value on the select tag */
});

So, the issue is the the SelectedIndex property of the DropDownList is always -1. What am I missing?

NOTE

I just discovered it doesn't seem to have any items on Postback.

John Pasquet
  • 1,824
  • 15
  • 20
  • I guess you have to set the `SelectedIndex` in `foreach (ListItem item in this.Items) ...` . Since Javascript changes the selection on the client side, this information is probably not passed on to the server. – Markus Deibel May 02 '17 at 14:06

1 Answers1

0

It turns out the problem seems to be that I was populating the items on Render. This was actually a Time Selector DropDownList, and I made the mistake of populating on Render. I moved the Population to the CreateChildControls() method, and it's working now.

John Pasquet
  • 1,824
  • 15
  • 20