A Bogus
A Bogus

Reputation: 3930

MVC 3 TextBoxes for 1 Model Property

On a form, I would like to use 3 text boxes to represent one Model property (a phone number). The phone number will be stored as a string like this - "614-555-4321". I want 3 text boxes to hold each of the three parts of the phone number that someone is entering. What is the easiest/best way to accomplish this?

Right now I have - @Html.TextBoxFor(m => m.ContactInfo.Phone)

How can I split it into 3 text boxes, then map it back to the ContactInfo.Phone property with "-" between the three parts of the phone number when the form is submitted?

Upvotes: 0

Views: 258

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

One way is to use three input properties in the view-model, and combine to get the phone number:

public string Area { get; set; }
public string Prefix { get; set; }
public string Suffix { get; set; }

public string Phone 
{
    get { return string.Format("({0}) {1}-{2}", Area, Prefix, Suffix); }
}

And:

(@Html.TextBoxFor(model => model.Area)) @Html.TextBoxFor(model => model.Prefix)[email protected](model => model.Suffix)

Upvotes: 1

Related Questions