简体   繁体   English

Angular JS与MVC4模型绑定失败的日期/日期时间?

[英]Angular JS with MVC4 model binding failing with date/datetime?

When using Angular JS to post back to the server with a complex object the datetime and datetime? 使用Angular JS使用复杂对象回发到服务器时的datetime和datetime? values do not bind correctly. 值无法正确绑定。 I have tried JSON.stringify to no avail. 我试过JSON.stringify无济于事。 I have posted a related question though possibly it was too general. 我发布了一个相关的问题,虽然它可能过于笼统。 What I really need to know is how to correctly pass those dates in. What I am currently doing is using workaround in js to convert the dates but I would rather not do that and simply get the dates in the form I need them when in Angular and then pass back the correct values. 我真正需要知道的是如何正确地传递这些日期。我目前正在做的是使用js中的变换来转换日期,但我宁愿不这样做,只需在Angular中获取我需要它们的表单中的日期然后传回正确的值。

How do you bind to those datetime/datetime? 你如何绑定到那些日期时间/日期时间? values correctly? 价值正确吗? Please see the following code example and Fiddler post results. 请参阅以下代码示例和Fiddler发布结果。

C# Class: 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: Angular JS控制器:

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 Post: 提琴手邮报:

HTTP/1.1 200 OK Cache-Control: private Content-Type: application/json; 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 字符集= UTF-8服务器:Microsoft-IIS / 8.0 X-AspNetMvc-版本:4.0 X-ASPNET-版本:4.0.30319 X-SourceFiles:????= UTF-的8B YzpcdXNlcnNcbmlja1xkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXFZhbGlkYXRpb25UZXN0XEhvbWVcR2V0UGVyc29uXDE = = X供电,通过: ASP.NET日期:2013年1月16日星期三14:48:34 GMT内容长度:124

{"FirstName":"Bob","LastName":"Smith","BirthDate":"/Date(695573315098)/","ApprovedForSomething":"/Date(1358261315098)/"} { “姓”: “鲍勃”, “名字”: “史密斯”, “出生日期”: “/日期(695573315098)/”, “ApprovedForSomething”: “/日期(1358261315098)/”}

This is the result on the server side. 这是服务器端的结果。 The datetime binds to a new datetime value which is not correct and the datetime? datetime绑定到一个不正确的新日期时间值和日期时间? is null. 一片空白。

在此输入图像描述

If someone has better solution then please feel free to update the answer. 如果有人有更好的解决方案,请随时更新答案。

There might be better solution out there but what I did is very simple workaround. 可能有更好的解决方案,但我所做的是非常简单的解决方法。 Just create an encapsulation property for DateTime object to string and use that for binding purpose. 只需为DateTime对象创建一个封装属性,然后将其用于绑定目的。

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);}
   }
}

Over http all objects are treated as strings and but ASP.NET is smart enough to provide Model Binding feature. 在http中,所有对象都被视为字符串,但ASP.NET足够聪明,可以提供模型绑定功能。 However it is unable to bind the JavaScript Date object to .NET DateTime object. 但是,它无法将JavaScript Date对象绑定到.NET DateTime对象。

More more robust approach is to use a model binder to work with all incoming dates. 更强大的方法是使用模型绑定器来处理所有传入日期。

public class DateTimeBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var name = bindingContext.ModelName;
        var value = bindingContext.ValueProvider.GetValue(name);
        if (value == null) 
            return null;

        DateTime date;
        if (DateTime.TryParse(value.AttemptedValue, null, DateTimeStyles.RoundtripKind, out date))
            return date;
        else
            return base.BindModel(controllerContext, bindingContext);
    }
}

Add in the global ASAX. 添加全局ASAX。

var dateTimeBinder = new DateTimeBinder();

ModelBinders.Binders.Add(typeof(DateTime), dateTimeBinder);
ModelBinders.Binders.Add(typeof(DateTime?), dateTimeBinder);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM