Search code examples
asp.net-core.net-corebootstrap-4

How to show two column values (surname + name) in c# net-core selectlist?


Expaination

I want to show customer name (column 2) and surname (column 3) in the same row into a select list.

The SQL table for Customer

{ Id, name, surname, age }

Question

How can this be done?

Frontend

 <div class="form-group">
 <label asp-for="Patient.CustomerId" class="control-label">Surname Name</label>
 <select asp-for="Patient.CustomerId" class ="form-control" asp-items="ViewBag.CustomerId"></select>

Backend

        public IActionResult OnGet()
    {
        ViewData["CustomerId"] = new SelectList(_context.Customers, "Id", "LastName", "FirstName");
        
        return Page();
    }

Solution

  • I think you should concatenate these two values into a single string. Something like this:

    public IActionResult OnGet()
    {
        var customers = _context.Customers.Select(c => new { Id = c.Id, FullName = c.Name + " " + c.Surname }).ToList();
        ViewData["CustomerId"] = new SelectList(customers, "Id", "FullName");
        
        return Page();
    }