0

In my registration FORM, I have to allow the user to put his date of birth. It is a requirement, that I show a SELECT for the day, a SELECT for the month and a SELECT for the year.

I have worked out a Html helper extension that creates that schema, and names the controls propertyName+".day", propertyName+".month" and propertyName+".year".

The idea is that in my view model, I define a DateTime property and then invoke this helper: @Html.DateSelect(m=>m.DateOfBirth) , but the problem is that I don't know how to merge the previous 3 properties in a DateTime again.

I would get 3 POST parameters named dateofbirth.day, dateofbirth.month and dateofbirth.year.

How would it be done in MVC3?

Thanks

vtortola
  • 34,709
  • 29
  • 161
  • 263

2 Answers2

2

You could write a custom model binder.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

You will need to use a custom model binder:

public class SplitDateTimeBinder : IModelBinder 
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

        ValueProviderResult day = bindingContext.ValueProvider.GetValue("propertyName.day");
        ValueProviderResult month = bindingContext.ValueProvider.GetValue("propertyName.month");
        ValueProviderResult year = bindingContext.ValueProvider.GetValue("propertyName.year");

        DateTime result = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));

        return user;
    }
}

and register it in Global.asax:

ModelBinders.Binders.Add(typeof(DateTime), new SplitDateTimeBinder());

I've used int.Parse() in the example but you'll probably want to use int.TryParse() and handle failed parses properly.

Adam Flanagan
  • 3,052
  • 23
  • 31