I got a model like this:
public class MainModel
{
public string Id {get;set;}
public string Title {get;set;}
public TimePicker TimePickerField {get;set;}
}
TimePicker
is an inner model which looks like this:
public class TimePicker
{
public TimeSpan {get;set;}
public AmPmEnum AmPm {get;set;}
}
I'm trying to create a custom model binding for inner model: TimePicker
The question is: How do I get values in custom model binder which was submitted in form into TimePicker
model fields?
If I try to get it like this:
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
I just get null
in value
.
I'm not sure how to implement the model binder correctly.
public class TimePickerModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
var result = new TimePicker();
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value != null)
{
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
try
{
//result = Duration.Parse(value.AttemptedValue);
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex.Message);
}
}
return result;
}
}
The following works for me.
Model:
Controller:
View (
~/Views/Home/Index.cshtml
):Custom editor template (
~/Views/Shared/EditorTemplates/TimePicker.cshtml
) which merges theTime
andAmPm
properties into a single input field and which will require a custom model binder later in order to split them when the form is submitted:and the model binder:
and finally register your model binder in
Application_Start
: