Athulya P D
Athulya P D

Reputation: 31

How do I get my dropdownlist to be in alphabetical order for my project in MVC?

I need to get the elements of my dropdown displayed in alphabetical order. Following is the code:

<select id="participantIds" data-placeholder="Select Participants" class="chosen-select" 
    multiple style="width:100%;" tabindex="4" 
    asp-for="UserIds"
    asp-items="@(new SelectList(ViewBag.Users, "Id", "Name"))">
I've tried to do it with `OrderBy but it doesn't seem to work for `ViewBag`? How do I do it with JavaScript or Jquery?

My ViewBag is of:

this.ViewBag.Users = await this._eventSessionService.GetAllUsers(eventSessionId);

Upvotes: 0

Views: 396

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 8312

Since ViewBag is dynamic therefore you cannot use the Orderby or other methods on a dynamic property

Now assuming that your ViewBag.Users is of List<Users>, you can cast the property to a known type collection and the extension method should then be available.

<select id="participantIds" data-placeholder="Select Participants" class="chosen-select" 
    multiple style="width:100%;" tabindex="4" 
    asp-for="UserIds"
    asp-items="@(new SelectList((ViewBag.Users as List<Users>).OrderBy(x=>x.Name), "Id", "Name"))">

An alternative is sorting the list in the controller before assigning it to the ViewBag:

var userList = await this._eventSessionService.GetAllUsers(eventSessionId);
this.ViewBag.Users = userList.OrderBy(x=>x.Name);

You can also use JQuery to sort our your list after it has been initialized:

var myList = $('#participantIds');
var selected = myList.val();
var opts_list = myList.find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
myList.html('').append(opts_list);
myList.val(selected);

Upvotes: 1

Related Questions