Mvc.net日期字段更改为默认日期

时间:2018-09-12 09:30:37

标签: .net asp.net-mvc

我在cshtml中有以下代码:

@Html.TextBoxFor(m => m.DateOfBirth, new { @class = "form-control", placeholder = "mm/dd/yyyy", id = "datepicker", @data_masked_input = "99/99/9999" })

DateOfBirth是datetime属性。

[DataType(DataType.Date)]
[Display(Name = "Date of Birth")]
public DateTime DateOfBirth { get; set; }` 

控制器代码如下:

public async Task<ActionResult> Login(Employee emp, string returnUrl)
{
    .....
}

Employee类包含DateOfBirth,它也是DateTime。由于某些原因,我将DOB属性的值作为默认日期,即“ 01/01/0001”。 这仅在特定的日期发生,例如当天是“ 19”。例如如果在属性字段中输入“ 11/19/1984”,则将DOB作为默认日期。

我的代码有问题吗?

1 个答案:

答案 0 :(得分:0)

这基本上是文化问题。为此,您需要在global.asax.cs文件中编写一个逻辑,如下所示。

httpClient

此逻辑用于设置区域性信息。 在以dd / MM / yyyy格式发布日期时,也会遇到同样的问题。为此,请在以下“ Appication_Start”部分的global.asax.cs文件中编写以下逻辑。

protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
        newCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        newCulture.DateTimeFormat.DateSeparator = "/";
        Thread.CurrentThread.CurrentCulture = newCulture;
        //ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
    }

并按照以下逻辑创建DateTimeModelBinder.cs文件

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());

请对其进行测试。

相关问题