Search code examples
c#asp.net-mvcvieweditorfor

How can I use multi properties in one field using EditorFor?


I have a Customer class:

public class Customer 
{
    public int Id { get; set; }
    public string Name { get; set; }
    string Surname { get; set; }
}

How can I use Name and Surname together in one field using Html.EditoFor ?

@Html.EditorFor(model => model.Customer.Name + Surename???? , new { htmlAttributes = new { @class = "form-control" } })

Solution

  • You can try to add NameWithSurname property to connected Nameand Surname value.

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    
        private string _NameWithSurname;
    
        public string NameWithSurname
        {
            get
            {
                _NameWithSurname = Name + Surname;
                return _NameWithSurname;
            }
            set {
                _NameWithSurname = value;
            }
        }
    }
    @Html.EditorFor(model => model.Customer.NameWithSurname  , new { htmlAttributes = new { @class = "form-control" } })
    

    NOTE

    Your Surname property might be public, otherwise it only can use in Customer class.