如何在asp.net MVC4中强制使用datetime的格式?在显示模式下,它按我想要的那样显示,但在编辑模式下,它不显示。我将displayfor和editorfor和applyformatineditmode=true与dataformatstring="{0:dd/MM/yyyy}“一起使用,这是我尝试过的:
在application_start()
中使用my culture和application_start()
实现文化和文化的全球化(两者都有)
我不知道如何强制它,我需要输入dd/MM/yyyy格式的日期,而不是默认值。
更多信息:我的视图模型是这样的
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
在视图中,我使用@Html.DisplayFor(m=>m.Birth)
,但这工作正常(我看到格式),输入日期我使用@Html.EditorFor(m=>m.Birth)
,但如果我尝试输入类似13/12/2000 is失败,错误,它不是一个有效的日期(12/13/2000和2000/12/13是预期的,但我需要dd/MM/yyyy)。
自定义模型绑定器是在application_start() b/c中调用的,我不知道还能在哪里。
在使用<globalization/>
时,我尝试过使用culture="ro-RO", uiCulture="ro"
和其他区域性,它们会给我带来dd/MM/yyyy。我还尝试在application_start()中以每个线程为基础设置它(这里有很多关于如何做到这一点的示例)。
对于所有将阅读这个问题:似乎Darin Dimitrov的答案将工作只要我没有客户验证。另一种方法是使用自定义验证,包括客户端验证。我很高兴在重新创建整个应用程序之前发现了这一点。
发布于 2012-06-30 17:20:55
啊哈,现在清楚了。您似乎在绑定回值时遇到了问题。而不是在视图上显示它。事实上,这是默认模型绑定器的错误。您可以编写并使用一个自定义的模型,它将考虑模型上的[DisplayFormat]
属性。我在这里演示了这样一个自定义模型绑定器:https://stackoverflow.com/a/7836093/29407
显然,一些问题仍然存在。这是我的完整设置,在ASP.NET MVC3和4RC上都可以很好地工作。
型号:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
查看:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Birth)
@Html.EditorFor(x => x.Birth)
@Html.ValidationMessageFor(x => x.Birth)
<button type="submit">OK</button>
}
在Application_Start
中注册自定义模型绑定器
ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());
和自定义模型绑定器本身:
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
现在,无论您在web.config (<globalization>
元素)或当前线程区域性中设置了什么区域性,在解析可为空的日期时,定制模型绑定器都将使用DisplayFormat
属性的日期格式。
发布于 2017-03-08 23:57:18
客户端验证问题可能是由于jquery.validate.unobtrusive.min.js中的MVC (即使在MVC5中也是如此)而发生的,因为以任何方式都不接受日期/日期时间格式。不幸的是,您必须手动解决它。
我的最终工作解决方案:
$(function () {
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
}
});
在此之前,您必须包括:
@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")
您可以使用以下命令安装moment.js:
Install-Package Moment.js
发布于 2016-08-11 16:56:16
感谢Darin,对于我来说,为了能够发布到create方法,它只有在我将BindModel代码修改为:
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
希望这能帮助到其他人。
https://stackoverflow.com/questions/11272851
复制相似问题