Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda