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

293 Views Asked by At

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" } })
2

There are 2 best solutions below

1
D-Shih On BEST ANSWER

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.

0
D Stanley On

You should either have the name split or combined - don't try to do both.

Suppose you do have a "full name" textbox, the value gets edited, and the user types Billy Bob Thornton. How then will it know how to split back into the first and last name fields?

You need to either use separate text boxes and properties, or use a single "name" property and a single textbox.

It's fine to combine the names when displaying data, but when editing it's more trouble than it's worth.