Skip to content

20 Get Full Name from FirstName and LastName

M. Fares edited this page Mar 20, 2018 · 1 revision

This procedure shows you how to get the fullname of a user from her firstname and lastname. Also it allows you to display the fullname in a dropdown list.

  1. Add a calculated property to your domain model. This property should be decorated with [NotMapped] attribute in order to avoid creating it in the database. There is no set method, since this is a calculated property.
public class Employee
{
  [NotMapped]
  public string FullName { get { return (FirstName + " " + LastName); } }
}
  1. To use this property in your controller, first, you need to create a list with Ids and FullName, then use it in a SelectList.
var list = db.Employees.ToList().Select(e => new { e.Id, e.FullName});
ViewBag.EmployeeId = new SelectList(list, "Id", "FullName");
  1. To use this property to display the fullname of a user, just calls it as regular property.
var fullname = db.Employee.FullName;

Clone this wiki locally