1

I have a Date variable in client side and I want to pass the Date variable to my controller at server side. I have passed as a normal field and the date is defaulting to 01-01-0001 12:00:00 AM.

help me to convert the date field with the right format.

2 Answers 2

1

ASP.NET MVC expects the DateTime value to be in the format of Thread.CurrentLanguage. Please check what language you are using.

Its like that because users might enter a Date in a TextBox and the they would enter the format of their language.

Like Pieter said: an easy way is to use a string in this case.

Another way is to use

protected void Application_BeginRequest(object sender, EventArgs e)
{
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}

in Global.Asax.

You can switch back to the language of the user in a filter after the ModelBinding happend:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
     {
             string language = //find a way to get the language - I have it in the route
             Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
             Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
         base.OnActionExecuting(filterContext)
     }

This way has some risks, but I find it easier in lots of situations if modelBinding uses InvariantCulture (think of decimal values in the route, datetime in the route...)

Sign up to request clarification or add additional context in comments.

Comments

0

I think it would be the easiest to pass the string representation of the date to the ASP.NET MVC action and attempt to parse it using DateTime.TryParse(..).

[HttpPost]
public ActionResult(string dateTimeString)
{
    DateTime tempDateTime;
    if(DateTime.TryParse(dateTimeString, out tempDateTime))
    {
       //Handle
    }
}

2 Comments

Actually the datetime is a filed of my model and I am using default modelbinder. is there any way to pass the date in correct format from the client?
Ohh, Check Malcolm Frexner's response :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.