MVC - 日期格式转换获取日期为空
MVC - Date Format Conversion getting Date as null
我正在使用 Jquery ui 日期选择器,日期格式设置为 dd/mm/yyyy
。
我的本地计算机服务器日期格式设置为 mm/dd/yyyy
。所以我在视图中转换了格式。
<input type="text" class="form-control datepicker" value="@string.Format("{0:dd/MM/yyyy}", DateTime.Now)" name="LoanDate" required />
在 POST 上的模型中,我得到 LoanDate
作为 null
。
如果我将我的本地计算机日期格式重置为 dd/mm/yyyy
,我会在我的控制器 POST 方法中得到 LoanDate
。
如何解决这个问题?
我就是这样解决的:-
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/
我正在使用 Jquery ui 日期选择器,日期格式设置为 dd/mm/yyyy
。
我的本地计算机服务器日期格式设置为 mm/dd/yyyy
。所以我在视图中转换了格式。
<input type="text" class="form-control datepicker" value="@string.Format("{0:dd/MM/yyyy}", DateTime.Now)" name="LoanDate" required />
在 POST 上的模型中,我得到 LoanDate
作为 null
。
如果我将我的本地计算机日期格式重置为 dd/mm/yyyy
,我会在我的控制器 POST 方法中得到 LoanDate
。
如何解决这个问题?
我就是这样解决的:-
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/