user3663854
user3663854

Reputation: 463

MVC model to accept big date

I'm referring to below link: stackoverflow.com/questions/18288675/display-datetime-value-in-dd-mm-yyyy-format-in-mvc4

Your model

  [Required(ErrorMessage = "Enter the Issued date.")]
  [DataType(DataType.Date)]
  public DateTime IssueDate { get; set; }

Razor Page

 @Html.TextBoxFor(model => model.IssueDate)
 @Html.ValidationMessageFor(model => model.IssueDate)

Jquery DatePickter

$(document).ready(function () {
    $('#IssueDate').datepicker({
        dateFormat: "dd/mm/yy",
        showStatus: true,
        showWeeks: true,
        currentText: 'Now',
        autoSize: true,
        gotoCurrent: true,
        showAnim: 'blind',
        highlightWeek: true
    });
});

Webconfig File

<system.web>
    <globalization uiCulture="en" culture="en-GB"/>
</system.web>

It works when using date format dd/MM/yyyy like 3/5/2015 but wont work when using date like 29/5/2015.

The textbox will show 29/5/2015 once we selected date from jquery datepicker. Just that when it post back to server, the model will show that the date is null (I'm using DateTime?). It will work just fine with 3/5/2015...

Any help?

EDIT:

I add below to my controller. When I postback, the function below will execute and it is showing en-GB. Then it will enter my other Action that suppose to handle the httppost, but it is showing en-US!

protected override void Initialize(System.Web.Routing.RequestContext requestContext) 
{ 
    base.Initialize(requestContext); 
    const string culture = "en-GB"; 
    CultureInfo ci =  CultureInfo.GetCultureInfo(culture);
    Thread.CurrentThread.CurrentCulture = ci;  
    Thread.CurrentThread.CurrentUICulture = ci; 
} 

Upvotes: 1

Views: 187

Answers (2)

Steve
Steve

Reputation: 9551

To add my comment as an answer:

To test, try giving it 5/29/2015 as the date. If this parses, then you have an issue with the culture of your application since it's trying to parse the date as an American format (mm/dd/yyyy) which 29/5/2015 fails.

Have a look in your application settings to see if en-US is being set anywhere, or if you accept the date to your controller as mm/dd/yyyy then parse it to your preferred format there.

Upvotes: 1

hbulens
hbulens

Reputation: 1969

I would start off with changing your Razor syntax from:

@Html.TextBoxFor(model => model.IssueDate)

to

@Html.EditorFor(model => model.IssueDate)

What is your browser's culture? It is as though the application is parsing the date to a different culture like en-US, which would then fail because there is no 29th month.

I think you'll also need to change your date format to dd/MM/yyyy. On MSDN there is a lot of information about this.

Upvotes: 0

Related Questions