Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass datetime from view to controller in asp.net MVC

Tags:

asp.net-mvc

Am trying to pass below data form my view to controller.

Edited

<script type="text/javascript">
    var pathname = 'http://' + window.location.host;
  var Student = [
  { Name: "Vijay", ID: 1, DOB: "2010-12-09T08:00:00.000Z" },
  { Name: "Anand", ID: 2, DOB: "2010-12-09T08:00:00.000Z" }
  ];

  $.ajax({
    url: pathname + "/Home/UpadetStu",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(Student),
    contentType: "application/json; charset=utf-8",
    success: function (result) { }, 
    failure: function (r, e, s) { alert(e); } 
  });

</script>



   [ObjectFilter(Param = "stuData", RootType = typeof(Stu[]))]
    public JsonResult UpadetStu(Stu[] stuData)
    {
        return this.Json(new { success = true });
    }

[DataContract]
public class Stu
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public DateTime? DOB { get; set; }

}

But in the controller am getting null for Name and ID , default datetime for DOB, I found that there is problem in passing datetime. Is there any better way to pass datetime from view to controller? do i miss any parsing?

like image 543
Amar Avatar asked Jun 25 '12 08:06

Amar


1 Answers

The problem is Thu Dec 9 13:30:00 UTC+0530 2010 can't be parsed into a valid datetime object in c#. You can try that by simply calling DateTime.Parse("Thu Dec 9 13:30:00 UTC+0530 2010") it will fail.

I would suggest that instead of returning that date format from the server you can better return the ISO 8601 format that looks like 2010-12-09T08:00:00.000Z.

You can easily convert the long datetime format into ISO 8601 from javascript by,

new Date("Thu Dec 9 13:30:00 UTC+0530 2010").toJSON();

If you are using JSON.NET library you can easily control the way in which the datetimes have to be serialized.

UPDATE:

<script type="text/javascript">

  var Student = [
  { Name: "Vijay", ID: 1, DOB: "2010-12-09T08:00:00.000Z" },
  { Name: "Anand", ID: 2, DOB: "2010-12-09T08:00:00.000Z" }
  ];

  $.ajax({
    url: "/Home/Index",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(Student),
    contentType: "application/json; charset=utf-8",
    success: function (result) { }, 
    failure: function (r, e, s) { alert(e); } 
  });

</script>

[HttpPost]
public ActionResult Index(Student[] students)
{
  ...
}
like image 190
VJAI Avatar answered Oct 23 '22 04:10

VJAI