Reputation: 1055
I have a form where I want the user to put it's phone number. However, the form looks like so:
[FormField-1] - [FormField-2] - [FormField-3]
Where there's three textboxes to facilitate the user in putting it in the format xxx-xxx-xxxx. However, my model class is:
class Person
{
[Required(ErrorMessage="Phone Mandatory!")]
public string phone {get; set;}
}
My view looks like so:
@model MvcApplication1.Models.Person
@using ( Html.BeginForm("Create", "Home"))
{
@Html.TextBoxFor( model => model.phone )
@Html.ValidationMessageFor( model => model.phone )<br />
<input type="submit" value="submit" />
}
How do I get around this, so that I don't have to have three different class properties to match the 3 different form fields that represent the phone number?
Thanks!
Upvotes: 1
Views: 620
Reputation: 148
Another solution might also be to just build the phone number value in the Action method with something like:
[HttpPost]
public ActionResult FormSubmit(Person person)
{
person.phone = Request.Form["FormField-1"] + Request.Form["FormField-2"] + Request.Form["FormField-3"];
...
}
Upvotes: 0
Reputation:
A more simple solution could be to use some javascript on the form to save the three separate values into one hidden input and bind that single input to the model.
Upvotes: 2
Reputation: 3326
You could use a custom model binder to achieve this.
Basically you register a type (which you create) to handle a specific model, and you can read in the posted form fields and populate your model manually, rather than getting the default model binder to do it. I think that's your only option in this case.
You can make it easier by inheriting from the default model binder, then just manually processing the more complex fields yourself.
Have a look at this for a bit more info on working with custom model binding: Custom Model Binder
Edit: You can also just accept a type of FormCollection in your action to read the raw posted data and process it in there, if you don't want to go the whole stretch with custom model binding, but it depends on how you want to expand your model in the future I guess.
Upvotes: 2