How to append datetime value to formdata and receive it in controller

微笑、不失礼 提交于 2019-12-01 02:09:15

问题


I want to know how I can pass datetime value through formdata and retrieve it in controller and convert it to DateTime in the controller

I've tried as below:

var formdata=new FormData();
fromDate = $('.from_date').datepicker('getUTCDate');
toDate = $('.to_date').datepicker('getUTCDate');

formdata.append("start", new Date(fromDate));
formdata.append("end", new Date(toDate));

and in $.ajax I am setting data:formdata

in my controller I receive it as below:

DateTime frmDate = Convert.ToDateTime(Request.Form["start"]).Date;
DateTime toDate = Convert.ToDateTime(Request.Form["end"]).Date;

But here I get a System.FormatException while trying to Convert to datetime and when I keep a watch for Request.Form["start"] then the value will be "Fri Mar 30 2015 05:30:00 GMT+0530 (Indian Standard Time)" but it considers it as string when retrieving from request.

Is it possible to pass datetime type through Request?


回答1:


You get FormatException because the date string is not formatted in recognized pattern for the .NET date parser. If we can be more specific about the format in javascript we can satisfy the .NET parser.

var datestr = (new Date(fromDate)).toUTCString();
formdata.append("start", datestr);

Either of these will give us an accepted format

  • toUTCString()
  • toISOString()

Now we parse the string in your server-side code

DateTime fromDate = Convert.ToDateTime(Request.Form["start"]).Date;

Depending on your machine's culture settings you may need to use DateTime.ParseExact() instead of Convert.ToDateTime().

Is it possible to pass datetime type through Request?

Along the pipeline from javascript to your controller action this will be converted to a string or integer anyway. We could return the tick (milisecond) representation for the DateTime but then you'd need to convert that to .NET ticks which uses a different epoch and nanosecond units.

Just stick to strings with standard formats.

More on parsing Date formats here.



来源:https://stackoverflow.com/questions/29287311/how-to-append-datetime-value-to-formdata-and-receive-it-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!