现在,我有一个如此定义的类:
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; }
}
Run Code Online (Sandbox Code Playgroud)
我想让用户也分别输入"2h"或"15m"2小时或15分钟.有没有办法可以允许这些类型的自定义输入?我只想创建一个文本框,然后对该传入值进行自定义检查,并将其正确地转换为TimeSpan.我不确定是否存在某种类型的"CustomConverter",就像"CustomValidator"属性一样.
如果有任何不清楚的地方,请告诉我.
提前致谢!
Ter*_*rry 15
我想我终于找到了它.根据Custom Model Binders,您只需在Global.asax中添加自定义模型绑定器即可.这就是我做的.我添加了一个类:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
然后我将这一行添加到我的Global.asax.cs中 public void Application_Start()
ModelBinders.Binders.Add(typeof(TimeSpan?), new TimeSpanModelBinder());
Run Code Online (Sandbox Code Playgroud)
奇迹般有效!