asp.net-mvc-3 – ASP.NET MVC3 – DateTime格式
发布时间:2020-05-23 06:54:05 所属栏目:asp.Net 来源:互联网
导读:我使用ASP.NET MVC 3。 我的ViewModel看起来像这样: public class Foo{ [DataType(DataType.Date)] [DisplayFormat(DataFormatString = {0:dd.MM.yyyy}, ApplyFormatInEditMode = true)] public DateTime StartDa
|
我使用ASP.NET MVC 3。
public class Foo
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}",ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
...
}
在我看来,我有这样的: <div class="editor-field">
@Html.EditorFor(model => model.StartDate)
<br />
@Html.ValidationMessageFor(model => model.StartDate)
</div>
StartDate以正确的格式显示,但是当我将它的值更改为19.11.2011并提交表单时,我得到以下错误消息:“值’19 .11.2011’对StartDate无效。 任何帮助将不胜感激! 解决方法您需要在web.config文件的全球化元素中设置正确的文化,其中dd.MM.yyyy是有效的datetime格式:<globalization culture="...." uiCulture="...." /> 例如,这是德语中的默认格式:de-DE。 更新: 根据你在评论部分的要求,你想保留en-US文化的应用程序,但仍然使用不同的格式的日期。这可以通过编写自定义模型绑定器来实现: 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);
}
}
您将在Application_Start中注册: ModelBinders.Binders.Add(typeof(DateTime),new MyDateTimeModelBinder()); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – Internet Explorer缓存asp.netmvc ajax结果
- asp.net-mvc – 如何拦截视图渲染以在所有部分视图上添加HT
- asp.net-mvc – WebService还是一个简单的MVC控制器?
- asp.net-mvc-4 – 如何永久教Visual Studio检测我的调试信息
- 在ASP.Net的URL中检索锚点链接
- asp.net – URL重写从/default.aspx到/
- asp.net-mvc – ASP.NET MVC Intellisense没有找到ViewData
- asp.net – 如何使用命令行msbuild部署VS2012网站项目,而无
- 从ASP.NET Web API中删除XML中的命名空间
- 在ASP.net C#中伪造浏览器请求
推荐文章
站长推荐
- asp.net – 为什么在FireFox中禁用时链接按钮不会
- asp.net – 向实体框架添加其他属性4代码首先是C
- asp.net-mvc – asp.NET:未知长度的MVC路径
- ef-code-first – 在WebAPI Controller中序列化E
- asp.net-mvc-3 – 将原始html转储到Telerik网格
- 企业ASP.NET MVC 3架构大纲
- 从ASP.NET应用程序写入IIS日志
- asp.net-mvc – 如何使用Simple Injector装饰ASP
- asp.net – 为什么aspx代码隐藏文件被声明为部分
- asp.net – RequiredFieldValidator在文本上放置
热点阅读
