我在 ASP .NET MVC 4 RC 中使用 Web API,并且有一个方法采用具有可为 null 的 DateTime 属性的复杂对象。我希望从查询字符串中读取输入的值,所以我有这样的东西:
public class MyCriteria
{
public int? ID { get; set; }
public DateTime? Date { get; set; }
}
[HttpGet]
public IEnumerable<MyResult> Search([FromUri]MyCriteria criteria)
{
// Do stuff here.
}
如果我在查询字符串中传递标准日期格式(例如 01/15/2012),则效果很好:
http://mysite/Search?ID=1&Date=01/15/2012
但是,我想为日期时间指定自定义格式(可能是 MMddyyyy)...例如:
http://mysite/Search?ID=1&Date=01152012
<小时/>
编辑:
我尝试应用自定义模型绑定(bind)器,但我没有成功地将其仅应用于 DateTime 对象。我尝试过的 ModelBinderProvider 看起来像这样:
public class DateTimeModelBinderProvider : ModelBinderProvider
{
public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(DateTime) || bindingContext.ModelType == typeof(DateTime?))
{
return new DateTimeModelBinder();
}
return null;
}
}
// In the Global.asax
GlobalConfiguration.Configuration.Services.Add(typeof(ModelBinderProvider), new DateTimeModelBinderProvider());
创建了新的模型绑定(bind)程序提供程序,但仅调用 GetBinder
一次(针对复杂模型参数,而不是针对模型中的每个属性)。这是有道理的,但我想找到一种方法,使其将我的 DateTimeModelBinder
用于 DateTime 属性,同时使用非 DateTime 属性的默认绑定(bind)。有没有办法覆盖默认的 ModelBinder 并指定每个属性的绑定(bind)方式?
谢谢!!!
最佳答案
考虑将 View 模型的 Date
属性设置为类型 string
然后编写一个实用函数来处理 View 模型类型和域模型类型之间的映射:
public static MyCriteria MapMyCriteriaViewModelToDomain(MyCriteriaViewModel model){
var date = Convert.ToDateTime(model.Date.Substring(0,2) + "/" model.Date.Substring(2,2) + "/" model.Date.Substring(4,2));
return new MyCriteria
{
ID = model.ID,
Date = date
};
}
或使用类似 AutoMapper 的工具,像这样:
在 Global.asax
//if passed as MMDDYYYY:
Mapper.CreateMap<MyCriteriaViewModel, MyCriteria>().
.ForMember(
dest => dest.Date,
opt => opt.MapFrom(src => Convert.ToDateTime(src.Date.Substring(0,2) + "/" src.Date.Substring(2,2) + "/" src.Date.Substring(4,2)))
);
在 Controller 中:
public ActionResult MyAction(MyCriteriaViewModel model)
{
var myCriteria = Mapper.Map<MyCriteriaViewModel, MyCriteria>(model);
// etc.
}
从这个例子来看,AutoMapper 似乎没有提供任何附加值。当您使用通常具有比此示例更多属性的对象配置多个或多个映射时,它的值(value)就出现了。 CreateMap 将自动映射具有相同名称和类型的属性,因此它可以节省大量输入,而且更加干燥。
关于asp.net-mvc - ASP.NET Web API 模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11875912/