Basically, my datepicker uses UK format of dd/mm/yyyy
. But when I submit the form, ASP.net is clearly using US format.
(will only accept days if less than 12, i.e. thinks it is the month.)
public ActionResult TimeTable(DateTime ViewDate)
Is there a way to force it to recognise a certain way?
Strangely though, other methods of insert seem to recognise the correct format.
"The parameters dictionary contains a null entry for parameter ViewDate
of non-nullable type System.DateTime
for method System.Web.Mvc.ActionResult Index(System.DateTime)
in Mysite.Controllers.RoomBookingsController
. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
Have a read of this. It gives a good explanation of what's happening and why it works as it does.
I'm in the situation where I know everyone using the site is in the UK so I can safely override the default DateTime
model binder:
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;
}
}
}
You need to use custom ModelBinder for your DateTime. I had that same problem as you.
Have you tried setting the Current Culture as 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With