Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!