Reputation: 6227
I've passed a Javascript DateTime picker date from a view to an MVC controller action.
The format of the string when passed to the controller action is Thu Jul 28 2016 17:05:00 GMT+0100
which causes an invalid operation exception converting String to DateTime.
in C#.
This is how I assign the value of the Date picker to the hidden field value:
$('#OutageStart').val(e.date)
How can you format JS Date string as a C# compatible DateTime?
The binding error is thrown in the C# custom model binder that tries to bind the JS Date string value to a Nullable<DateTime>
:
public class DateTimeBinder : System.Web.Mvc.IModelBinder
{
public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
return value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
}
}
Upvotes: 3
Views: 1312
Reputation: 11963
alternatively you can use timestamp for the conversion and user's timezone won't effect your result
in js
myDateObject.getTime() //-> outputs a timestamp (integer)
in c# (if you have .NET 4.6+)
DateTimeOffset.FromUnixTimeSeconds(timestamp);
otherwise
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(timestamp).ToLocalTime();
Upvotes: 2
Reputation: 479
In js
Var date = $.datepicker.formatdate('dd/mm/yy',new Date(datepickerdate)
In c#
Void convertdate(string javascriptdateinstringformat){
datetime.parse(javascriptdateinstringformat) ; }`
Upvotes: 0
Reputation: 703
Have you tried using new Date() function ? In normal binding this works but in your custom value i'm not sure but do try if this could help.
$('#OutageStart').val(new Date(e.date));
Upvotes: 0