加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在ASP.NET MVC应用程序中更改日期格式

发布时间:2020-12-15 23:07:23 所属栏目:asp.Net 来源:网络整理
导读:我需要将日期格式更改为dd.MM.yyyy.我得到客户端验证错误,因为ASP.NET MVC日期格式不同于我在服务器上的期望. 为了改变ASP.NET MVC日期格式,我试过: Web.config文件: globalization uiCulture="ru-RU" culture="ru-RU" / 模型: [DataType(DataType.Date)]
我需要将日期格式更改为dd.MM.yyyy.我得到客户端验证错误,因为ASP.NET MVC日期格式不同于我在服务器上的期望.

为了改变ASP.NET MVC日期格式,我试过:

Web.config文件:

<globalization uiCulture="ru-RU" culture="ru-RU" />

模型:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}",ApplyFormatInEditMode = true)]
public DateTime? ServiceCreatedFrom { get; set; }

编辑器模板:

@model DateTime?
@Html.TextBox(string.Empty,(Model.HasValue 
    ? Model.Value.ToString("dd.MM.yyyy")
    : string.Empty),new { @class = "date" })

视图:

@Html.EditorFor(m => m.ServiceCreatedFrom,new { @class = "date" })

甚至Global.asax:

public MvcApplication()
{
    BeginRequest += (sender,args) =>
        {
            var culture = new System.Globalization.CultureInfo("ru");
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        };
}

没有什么对我有用

解决方法

以下应该工作:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}",ApplyFormatInEditMode = true)]
public DateTime? ServiceCreatedFrom { get; set; }

并在您的编辑器模板中:

@model DateTime?
@Html.TextBox(
    string.Empty,ViewData.TemplateInfo.FormattedModelValue,new { @class = "date" }
)

接着:

@Html.EditorFor(x => x.ServiceCreatedFrom)

您传递给EditorFor调用的第二个参数不会执行您的想法.

对于此自定义编辑器模板,由于您在视图模型属性上明确指定了格式,< worldwide>元素在你的web.config和当前的线程文化将有0效果.当前的线程文化与标准模板一起使用,当您没有使用[DisplayFormat]属性覆盖格式时.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读