Dropdownlist with unique MVC values

Asked

Viewed 415 times

4

My class Galeria possessed a foreign key with Album as there is a 1-n ratio and each photo in the item Galeria owned respectively a Album. Given this, in the CMS I created I give the possibility of the user to relate a photo to an Album at the time of upload. For this, my View is like this:

<div class="editor-label">
   Cursos @Html.DropDownList("Album", ViewData["Cursos"] as SelectList)
</div>

And my Controller:

AlbumAplicacao bdAlbum;
   bdAlbum = AlbumAplicacaoConstrutor.AlbumAplicacaoEF();
   var list = new SelectList(bdAlbum.ListarTodos().OrderByDescending(x => x.Nome), "ID", "Nome");
   ViewData["Cursos"] = list;

Meu Dominio:

public class CONGRESSO_Galeria
{
    public int ID { get; set; }

    public string Descricao { get; set; }

    public string Foto { get; set; }

    public virtual CONGRESSO_Album CONGRESSO_Album { get; set; }

}

My problem is that I am getting several identical values in Dropdown. I tried to use Trim() and filter using the Distinct() but I was unsuccessful.

I noticed that the problem was generated because when recording the item, I am recording again an Album. I will correct this, but there have been hundreds of entries and thanks to this, I need to find a way to change the display.

1 answer

2


Rafael.

Try this:

[Controller]
     var list = new SelectList(bdAlbum.ListarTodos().OrderByDescending(x => x.Nome).GroupBy(x => x.Nome.ToLower().Trim()).Select(y => y.First()) , "ID", "Nome");

This way you will group all the same values.

The correct thing is to prevent duplicate values from being inserted into your bank.

  • Diego, it didn’t work. The order of OrderBy and of GroupBy was wrong, even correcting and applying : var list = new SelectList(bdAlbum.ListarTodos().OrderByDescending(x => x.Nome).GroupBy(x => x.Nome.ToLower().Trim()), "ID", "Nome"); did not succeed

  • @Rafaelbarbosa, I edited the answer. I had forgotten the . Select().

  • It worked. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.