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

I am trying to pass below the data form of my view to the 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, I get null for Name and ID, by default datetime for DOB, I found that there is a problem with passing datetime. Is there a better way to pass the date and time from the view to the controller? am I missing parsing?

+6
source share
2 answers

Thu Dec 9 13:30:00 UTC+0530 2010 cannot be parsed into a valid datetime object in C #. You can try this by simply typing DateTime.Parse("Thu Dec 9 13:30:00 UTC+0530 2010") , it will fail.

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

You can easily convert long datetime format to ISO 8601 from javascript,

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

If you use the JSON.NET library, you can easily control how dates should 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) { ... } 
+5
source

If the studentData object in your controller is NULL, JSON.stringify (Student) creates an object that is not proper JSON or an object that cannot be parsed for your Stu object.

Make sure your JS Student object is correct, and then verify that the JSON you create is executing JSON.stringify

0
source

Source: https://habr.com/ru/post/918922/


All Articles