Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda