Marcin Rakoczy
Marcin Rakoczy

Reputation: 47

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

Upvotes: 1

Views: 344

Answers (2)

D Stanley
D Stanley

Reputation: 152491

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.

Upvotes: 1

D-Shih
D-Shih

Reputation: 46219

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.

Upvotes: 1

Related Questions