ASP.NET MVC 3自定义类型转换 [英] 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; }
}
我想允许用户还输入小时或 15米为分别为2小时,或15分钟。有没有一种办法可以让这些类型的自定义输入?我想只是建立一个文本框,然后做针对传入值自定义检查和正确的投它一个时间跨度。我不知道是否有某种类型的CustomConverter很像的CustomValidator属性。
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.
谢谢!
推荐答案
我想我终于找到了。据自定义模型绑定你可以再补充在Global.asax一个自定义模型粘合剂。下面是我做的。我添加了一个类,例如:
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.
}
}
然后我加入这行到我的Global.asax在公共无效的Application_Start的.cs()
ModelBinders.Binders.Add(typeof(TimeSpan?), new TimeSpanModelBinder());
工程就像一个魅力!
Works like a charm!
这篇关于ASP.NET MVC 3自定义类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!