Is it possible to insert two results in the same Dropdownlist? C#

Asked

Viewed 36 times

-2

In my code, there is a page for sales registration where it is necessary to enter some information as for example which customer made the purchase.


Controller Venda:

// GET: Vendas/Create
        [Authorize]
        public ActionResult Create()
        {
            ViewBag.ClienteId = new SelectList(db.Clientes, "Id", "CPF");
            ViewBag.ProdutoId = new SelectList(db.Produtos, "Id", "Nome");
            return View();
        }

        // POST: Vendas/Create
        // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para 
        // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Data,Fiado,QtdVendida,ValorVenda,ClienteId,ProdutoId")] Venda venda)
        {
            if (ModelState.IsValid)
            {
                db.Vendas.Add(venda);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ClienteId = new SelectList(db.Clientes, "Id", "CPF", venda.ClienteId);
            ViewBag.ProdutoId = new SelectList(db.Produtos, "Id", "Nome", venda.ProdutoId);
            logger.Info("Criou uma nova Venda.");
            return View(venda);
        }

View Create:

<div class="form-group">
            <p class="control-label col-md-2">Cliente</p>
            <div class="col-md-10">
                @Html.DropDownList("ClienteId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ClienteId, "", new { @class = "text-danger" })
            </div>
        </div>

For this I use a Dropdownlist that displays the CPF’s of customers already registered, however I wanted to know if in the options of the CPF’s is also possible to display the names of the respective clients next to the CPF.

Print do cadastro

1 answer

0

Yes, all you have to do is compose the Text attribute from SelectList, say the Customer’s name is on the Name property..

var clientesDropList = db.Clientes
                        .Select(x => new { Id = x.Id, Descricao = $"{x.CPF} - {x.Nome}" })
                        .ToList();

ViewBag.ClienteId = new SelectList(clientesDropList, "Id", "Descricao", venda.ClienteId);

Browser other questions tagged

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