How to order dropdown list items ?

Hello,
I am using a dropdown list control in my application. It is bound to remote datasource by url adaptor. On ActionComplete event handler I am adding one more object to dropdown list control by using this code : "this.addItem({ Id: -1, CategoryName: "All Categories" })". It works well, but I need that this new object must be in first position, not at the bottom of the list.

Please, advice.
Thanks.

3 Replies

PO Prince Oliver Syncfusion Team January 23, 2018 09:06 AM UTC

Hi Alex, 

Thank you for Contacting Syncfusion forums. 

To addItem at the first position in the DropDownList, Kindly refer to the following “How to” section in the UG documentation: https://help.syncfusion.com/js/dropdownlist/howto#how-can-i-add-items-in-ejdropdownlist-at-the-first-place-in-list 

As per your scenario, since you are adding item once the remote data loads, you need to use the dataBound event to access the data that is bound to the DropDownList control. Then you need to add the new item to the DataSource in first position and rebind the data to the control. To avoid script looping, we are using a global flag variable to distinguish between the initial and other calls. Kindly refer to the following code. 

@Html.EJ().DropDownList("skillsets").DropDownListFields(f => f.Text("CategoryName").Value("Id")).WatermarkText("Select your skill").Width("100%").ClientSideEvents(e=> e.Create("oncreate").DataBound("ondataBound")) 
 
<script type="text/javascript"> 
        var target, initialLoad = true; 
        function oncreate() { 
            // DataManager creation 
            var dataManger = ej.DataManager({ 
                url: "getData" 
            }); 
            // Query creation 
            var query = ej.Query(); 
 
            this.setModel({ 
                dataSource: dataManger, 
                query: query, 
            }); 
        } 
        function ondataBound(args) { 
            if (initialLoad == true) { 
                initialLoad = false; 
                args.data.splice(0, 0, { Id: "-1", CategoryName: "All Categories" }); 
                this.setModel({ dataSource: args.data }); 
            } 
            initialLoad = false; 
        } 
</script> 

We have prepared a sample for your reference, please find the sample from the following location: http://www.syncfusion.com/downloads/support/forum/135561/ze/DDLAddItemInFirst1863073198 

Regards, 
Prince 



AL Alex January 23, 2018 11:02 AM UTC

Thank You !
Your example was very helpful for me.


PO Prince Oliver Syncfusion Team January 24, 2018 03:51 AM UTC

Hi Alex, 

Most welcome. We are glad to help you. 

Regards, 
Prince 


Loader.
Up arrow icon