【问题标题】:MVC - Date Format Conversion getting Date as nullMVC - 日期格式转换获取日期为空
【发布时间】:2015-04-16 14:32:24
【问题描述】:

我正在使用 Jquery ui datepicker,dateFormat 设置为dd/mm/yyyy。 我的本地机器服务器日期格式设置为mm/dd/yyyy。所以我在 View 中转换了格式。

<input type="text" class="form-control datepicker" value="@string.Format("{0:dd/MM/yyyy}", DateTime.Now)" name="LoanDate" required  />

在我的 POST 模型中,我得到 LoanDatenull

如果我将本地机器日期格式重置为 dd/mm/yyyy,我会在控制器 POST 方法中获得 LoanDate

如何解决这个问题?

【问题讨论】:

  • 您有 2 个选项,在您的服务器中使用 mm/dd/yyyy 格式,或者在发布数据之前将该日期转换为 mm/dd/yyyy
  • 如何在没有字段名称的情况下发布数据?我会使用 javascript 即时转换。
  • 请以 49 票(或更多)票查看答案:stackoverflow.com/questions/2356601/…
  • value=" @DateTime.Now.ToString("dd/MM/yyyy")"

标签: c# jquery asp.net-mvc date


【解决方案1】:

这就是我解决它的方法:-

public class UTCDateTimeModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            // Check if the DateTime property being parsed is not null or "" (for JSONO
            if (value.AttemptedValue != null && value.AttemptedValue != "")
            {
                // Parse the datetime
                var dt = DateTime.ParseExact(value.AttemptedValue, "dd/MM/yyyy", CultureInfo.InvariantCulture);                
                return dt;
            }
            else
            {
                return null;
            }
        }
    }

在 Global.asax - Application_Start() 中:-

var binder = new UTCDateTimeModelBinder();
ModelBinders.Binders.Add(typeof(DateTime), binder);
ModelBinders.Binders.Add(typeof(DateTime?), binder);

现在我在我的模型中以dd/MM/yyyy 格式获得LoanDate 值。

http://www.martin-brennan.com/custom-utc-datetime-model-binding-mvc/

【讨论】:

    猜你喜欢
    • 2018-02-12
    • 2023-03-30
    • 2011-08-13
    • 2021-11-25
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    相关资源
    最近更新 更多