[英]Converting dd/MM/yyyy string format date to MM/dd/yyyy date format in ASP.NET Mvc
[英]ASP.NET MVC3: Force controller to use date format dd/mm/yyyy
基本上,我的datepicker使用英國格式的dd/mm/yyyy
。 但是當我提交表單時,ASP.net顯然使用美國格式。 (只接受少於12天,即認為是月份。)
public ActionResult TimeTable(DateTime ViewDate)
有沒有辦法強迫它識別某種方式?
奇怪的是,其他插入方法似乎都能識別正確的格式。
“參數字典包含參數提供一個空條目ViewDate
非空類型System.DateTime
為方法System.Web.Mvc.ActionResult Index(System.DateTime)
在Mysite.Controllers.RoomBookingsController
。一個可選參數必須是引用類型,可以為空的類型,或者聲明為可選參數。“
有讀這個 。 它可以很好地解釋發生了什么以及它為什么會起作用。
我知道每個使用該網站的人都在英國,所以我可以安全地覆蓋默認的DateTime
模型綁定器:
public class DateTimeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
if (String.IsNullOrEmpty(date))
return null;
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));
try
{
return DateTime.Parse(date);
}
catch (Exception)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName));
return null;
}
}
}
您需要為DateTime使用自定義ModelBinder。 我和你有同樣的問題。
您是否嘗試將當前文化設置為en-GB?
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
CultureInfo cultureInfo = CultureInfo.GetCultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
}
基本上,我的datepicker使用英國格式的dd / mm / yyyy
初學者的錯誤。 它應該使用瀏覽器設置的任何格式。 問題不是格式,而是客戶端和服務器之間的格式不同。 服務器應該根據協商的區域設置發出格式化日期的代碼,然后服務器也會使用它來解析它。
但是當我提交表單時,ASP.NET顯然使用美國格式。
不。 這就是說,當我服用香料時,它總是鹽,然后你總是加鹽。 您的服務器接受當前協商的文化 - 除非您修改設置 - 在客戶端和服務器之間協商。 檢查線程當前文化何時應該進行解析以查看它的設置。
你能行的:
全局(在Application_Start()下的global.asax中):
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
方法:
public ActionResult TimeTable([Binder(typeof(DateTimeModelBinder)]DateTime ViewDate)
對於自定義模型類 - 啊不,沒有可能性導致您使用struct DateTime ;-)
啊,對不起我無法在Adams帖子上添加評論 - 這是基於他的代碼。
從我的BindigTools綁定DateTime? (Nullable),基於一些書籍樣本 - Pro MVC3
public static DateTime? GetValueNDateTime(ModelBindingContext context, string searchPrefix, string key, string format)
{
ValueProviderResult vpr = context.ValueProvider.GetValue(searchPrefix + key);
DateTime outVal;
if (DateTime.TryParseExact(vpr.AttemptedValue, format, null, System.Globalization.DateTimeStyles.None, out outVal))
{
return outVal;
}
else
{
return null;
}
}
它使用精確解析,因此您不應該對解析日期有任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.