asp.net-mvc - 带有 MVC4 模型绑定(bind)的 Angular JS 因日期/日期时间而失败?

标签 asp.net-mvc asp.net-mvc-4 angularjs

当使用 Angular JS 将日期时间和日期时间的复杂对象回发到服务器时?值未正确绑定(bind)。我试过 JSON.stringify 无济于事。我已经发布了一个相关问题,尽管它可能太笼统了。我真正需要知道的是如何正确传递这些日期。我目前正在做的是在 js 中使用变通方法来转换日期,但我宁愿不这样做,只是在 Angular 中以我需要的形式获取日期然后传回正确的值。

你如何绑定(bind)到那些日期时间/日期时间?值(value)观正确吗?请查看以下代码示例和 Fiddler 发布结果。

C# 类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public DateTime? ApprovedForSomething { get; set; }
}

Angular JS Controller :

function PersonController($scope, $http) {
    $scope.getPerson = function () {
        $http.get('../../Home/GetPerson/1').success(function (data) {
            $scope.Person = data;
        });
    }
    $scope.updateApprovedForSomething = function () {
        $http.post('../../Home/UpdatePerson', { person: $scope.Person }).success(function (data) {
            console.log(data);
        });
    }
}

fiddler 帖子:

HTTP/1.1 200 OK Cache-Control: private Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/8.0 X-AspNetMvc-Version: 4.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNcbmlja1xkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXFZhbGlkYXRpb25UZXN0XEhvbWVcR2V0UGVyc29uXDE=?= X-Powered-By: ASP.NET Date: Wed, 16 Jan 2013 14:48:34 GMT Content-Length: 124

{"FirstName":"Bob","LastName":"Smith","BirthDate":"/Date(695573315098)/","ApprovedForSomething":"/Date(1358261315098)/"}

这是服务器端的结果。日期时间绑定(bind)到一个不正确的新日期时间值和日期时间?一片空白。

enter image description here

最佳答案

如果有人有更好的解决方案,请随时更新答案。

可能有更好的解决方案,但我所做的是非常简单的解决方法。 只需为 DateTime 对象创建一个封装属性到字符串并将其用于绑定(bind)目的。

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public DateTime? ApprovedForSomething { get; set; }
    public DateTime BirthDateAsString 
    {
        get { return BirthDate.ToShortDateString();}
        set { DateTime.Parse(value, BirthDate);}
   }
}

在 http 上,所有对象都被视为字符串,但 ASP.NET 足够智能,可以提供模型绑定(bind)功能。但是,它无法将 JavaScript Date 对象绑定(bind)到 .NET DateTime 对象。

关于asp.net-mvc - 带有 MVC4 模型绑定(bind)的 Angular JS 因日期/日期时间而失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14467277/

相关文章:

javascript - getJSON 类型错误 e 未定义

由于在发送到服务器之前添加了 URL,AJAX 请求无效

entity-framework - 使用显式包含时,即使在 ProxyCreation false 之后,也会出现 JSON 序列化 Entity Framework 自引用循环错误

javascript - jQuery ajax 表单错误

javascript - Angular promise 然后发出

c# - MVC3 Visual Studio 2010 中的嵌套文件夹

c# - OnModelCreating Entity Framework Core

c# - 新 View 或局部 View

javascript - 如何在 Angular Controller 中应用foreach循环

angularjs - 在 ng-model-debounce 之后显示 Angular ui 工具提示?