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

问题描述 投票:1回答:1

我在cshtml中有以下代码:

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

这里DateOfBirth是一个日期时间属性。

[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作为默认日期。

我的代码有问题吗?

.net asp.net-mvc
1个回答
0
投票

这基本上是一个文化问题。为此,您需要在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());
    }

该逻辑用于设置文化信息。以dd / MM / yyyy格式发布日期时将面临同样的问题。为此,请在“Appication_Start”部分的global.asax.cs文件中编写如下逻辑,如下所示。

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

并创建DateTimeModelBinder.cs文件,如下所示

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var holderType = bindingContext.ModelMetadata.ContainerType;
        if (bindingContext.ModelMetadata.PropertyName != null)
        {
            var property = holderType.GetProperty(bindingContext.ModelMetadata.PropertyName);
            var displayFormat = string.Empty;
            displayFormat = "dd/MM/yyyy";

            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);
    }

请测试一下。

© www.soinside.com 2019 - 2024. All rights reserved.