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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With