Pick only one item from an ASP.NET MVC list

Asked

Viewed 148 times

-1

How do I pick up only one item from a list? for example:

I have a class called Cliente, my client has a collection of Contatos

Public class Cliente
{
public Int Id {get ;set;}

public Icollection<Contatos> Contato {get ;set }
}

in my view, I bring the customer already with the included contacts, what I want to know is if I get you only one item from that list. even if it is the first, registered.

@foreach(cliente in Model)
{
<td>@item.Id</td>
<td>contatos // aqui quero pegar só um contato da coleção<td>
}
  • 1

    but what is the criterion? you need to know what you want, the first? Model.FirstOrDefault(), the client with Id 3? Model.FirstOrDefault(c => c.Id == 3).... are examples, give more details

  • Would not be Model.Contatos.FirtOrDefault ? I want to get the first item on the list

  • 1

    yes that’s right, I put only examples. If it’s just the first one it already solves, or if I’m sure the list is filled, First()

1 answer

1


friend you can do in two ways, are the ones I know and apply in the solutions here:

1° option:

<label>Categoria</label>
<select asp-for="Establishment.Id_Category" asp-items="@(new SelectList(Model.Category,"idCategory","CategoryName"))" id="category" class="form-control" required>
<option selected disabled>Categoria</option>
</select>

2° option

<label for="categoria">Categoria*</label>
<select id="categoria" name="categoria" class="form-control">
 <option selected>Selecione uma Categoria</option>
 @foreach (var C in ViewBag.ListaCategoria)
 {
   <option value="@(C.idCategoria)">@(C.nomeCategoria)</option>
 }
 </select>

both examples provide a list of categories for the client, and when the user selects a category, what goes to the server is the ID of that category, the ID would be a category identifier in the database to make the relationship between tables and such...

in your case what matters to you is the value, is in it that you put what can identify all the data, if you are going to do a search in the bd, can be an ID for example...

Browser other questions tagged

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