我试图将以下数据从我的视图传递给控制器.
编辑
<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; }
}
Run Code Online (Sandbox Code Playgroud)
但是在控制器中,对于名称和ID,DOB的默认日期时间变为空,我发现传递datetime时出现问题.有没有更好的方法将datetime从视图传递到控制器?我是否会错过任何解析?
问题是Thu Dec 9 13:30:00 UTC+0530 2010无法解析为c#中的有效日期时间对象.您可以通过简单地调用DateTime.Parse("Thu Dec 9 13:30:00 UTC+0530 2010")它来尝试它将失败.
我建议您不要从服务器返回该日期格式,而是可以更好地返回看起来像的ISO 8601格式2010-12-09T08:00:00.000Z.
您可以轻松地将长日期时间格式从javascript转换为ISO 8601,
new Date("Thu Dec 9 13:30:00 UTC+0530 2010").toJSON();
Run Code Online (Sandbox Code Playgroud)
如果您使用的是JSON.NET库,则可以轻松控制日期时间的序列化方式.
更新:
<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)
{
...
}
Run Code Online (Sandbox Code Playgroud)