How to list products from a single restaurant?

4

I have registered my products at a particular restaurant. Being Restaurant (1) and Products (N), I have several products registered in a restaurant.

How do I list these products for each restaurant?

This is the default Action:

public ActionResult Cardapio()
    {

        return View(db.Produtos.ToList());
    }
    
asked by anonymous 28.09.2016 / 05:23

1 answer

5

I would do so:

public ActionResult Cardapio(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var restaurante = db.Restaurantes
                        .Include(r => r.Produtos)
                        .FirstOrDefault(r => r.RestauranteId == id);

    if (restaurante == null)
    {
        return HttpNotFound();
    }

    return View(restaurante.Produtos.ToList());
}

Usage:

http://localhost:porta/Restaurantes/Cardapio/1 

Where 1 is the Id of the Restaurant.

Links:

@Html.ActionLink"Cardápio", "Cardapio", "Restaurantes", new { id = Model.RestauranteId })

Or:

<a href="@Url.Action("Cardapio", "Restaurantes", new { id = Model.RestauranteId })">Ver Cardápio</a>
    
28.09.2016 / 05:41