在ASP.NET MVC中,绑定时的格式化日期通常是通过数据注解(Data Annotations)或模型绑定(Model Binding)来实现的。以下是一个简单的示例,展示了如何在ASP.NET MVC中实现绑定时的格式化日期:
public class Person
{
public int Id { get; set; }
[Display(Name = "Birth Date")]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
}
@Html.EditorFor(model => model.BirthDate)
using System.Globalization;
using System.Web.Mvc;
public class DateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value != null && !string.IsNullOrEmpty(value.AttemptedValue))
{
DateTime date;
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
using System.Web.Mvc;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
}
}
这样,在ASP.NET MVC中绑定时的格式化日期就实现了。
领取专属 10元无门槛券
手把手带您无忧上云