views:

23

answers:

2

I have an input form that is bound to a model. The model has a TimeSpan property, but it only gets the value correctly if I enter the time as hh:mm or hh:mm:ss. What I want is for it to capture the value even if it's written as hhmm or hh.mm or hh.mm.ss or ... I want many different formats to be parsed correctly. Is this possible?

Thanks!

+2  A: 

Yes - write a custom model binder for your model object. There's an thread about just that subject here on SO: http://stackoverflow.com/questions/2343913/asp-net-mvc2-custom-model-binder-examples

Lazarus
Great! This is the way to go...
Carles
A: 

For the record, here's how I did it:

using System;
using System.Globalization;
using System.Web.Mvc;

namespace Utils.ModelBinders
{
    public class CustomTimeSpanModelBinder : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
            var form = controllerContext.HttpContext.Request.Form;

            if (propertyDescriptor.PropertyType.Equals(typeof(TimeSpan?)))
            {
                var text = form[propertyDescriptor.Name];
                DateTime value;
                if (DateTime.TryParseExact(text, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
                        SetProperty(controllerContext,bindingContext,propertyDescriptor,value.TimeOfDay);
                else if (DateTime.TryParseExact(text, "HH.mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, value.TimeOfDay);
                else if (DateTime.TryParseExact(text, "HHmm", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, value.TimeOfDay);
                else if (DateTime.TryParseExact(text, "HH,mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, value.TimeOfDay);
                else if (DateTime.TryParseExact(text, "HH", CultureInfo.InvariantCulture, DateTimeStyles.None, out value))
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, value.TimeOfDay);
            }
            else
            {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
        }
    }
}
Carles