Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3: Force controller to use date format dd/mm/yyyy

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."

like image 703
IAmGroot Avatar asked Dec 12 '11 13:12

IAmGroot


3 Answers

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;
        }
    }
}
like image 119
Adam Flanagan Avatar answered Nov 13 '22 06:11

Adam Flanagan


You need to use custom ModelBinder for your DateTime. I had that same problem as you.

like image 38
Gumowy Kaczak Avatar answered Nov 13 '22 06:11

Gumowy Kaczak


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;                    
 }
like image 2
Sebastian Piu Avatar answered Nov 13 '22 06:11

Sebastian Piu