Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 Custom Type Conversion

Right now, I have a class defined as such:

public class Task
{
    public Guid TaskId { get; set; }
    public string TaskName { get; set; }

    [DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = @"{0:hh\:mm}")]
    public TimeSpan? TimeRequired { get; set; }
}

I would like to allow the user to also enter "2h" or "15m" for 2 hours or 15 minutes respectively. Is there a way I can allow these types of custom inputs? I was thinking of just creating a text box and then doing a custom check against that incoming value and cast it correctly to a TimeSpan. I wasn't sure if there was some type of "CustomConverter" much like the "CustomValidator" attribute.

Please let me know if anything is unclear.

Thanks in advance!

like image 489
Terry Avatar asked Jul 28 '11 15:07

Terry


1 Answers

I think I finally found it. According to Custom Model Binders you can just add a custom model binder in the Global.asax. Here is what I did. I added a class as such:

public class TimeSpanModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        string attemptedValue = value.AttemptedValue;

        // Custom parsing and return the TimeSpan? here.
    }
}

and then I added this line to my Global.asax.cs in public void Application_Start()

ModelBinders.Binders.Add(typeof(TimeSpan?), new TimeSpanModelBinder());

Works like a charm!

like image 108
Terry Avatar answered Nov 09 '22 02:11

Terry