MVC 4单页应用和DateTime [英] MVC 4 Single Page Application and DateTime

查看:335
本文介绍了MVC 4单页应用和DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然与MVC 4的新单页的应用工具打转转,我注意到,没有一个我已经找到了例子包含正在更新背透的WebAPI一个DateTime的一个例子。我很快发现了原因。

While playing around with MVC 4's new single page application tooling, I noticed that none of the examples I have found contains an example of a DateTime being updated back through the WebApi. I soon found out why.

我一开始就产生所提供的范本标准SPA。然后我打开了TodoItem.cs并增加了一个DateTime字段。然后,我产生了控制器的意见的指示。 (如果没有日期时间字段,一切工作就好了)。

I started by generating the standard SPA from the template provided. I then opened up TodoItem.cs and added a DateTime field. Then I generated the controller as instructed by the comments. (Without the datetime field, everything works just fine).

生成的一切,我开始了应用程序,并导航到控制器指数后(我叫控制器任务)。我和0的记录得到了网格页面预期并点击添加按钮。我被带到编辑页面如预期,并进入一些数据,包括在我的闪亮的新日期时间字段的日期。然后点击保存。

After everything generated, I started the app and navigated to the controller index (I called the controller "tasks"). I got the grid page with 0 records as expected and clicked on the add button. I was taken to the edit page as expected and entered some data including a date in my shiny new datetime field. Then clicked save.

制作了一个错误说:

服务器错误:HTTP状态code:500,消息:有一个错误反序列化的类型System.Web.Http.Data.ChangeSetEntry []的对象。日期时间内容'01 / 01/2012年所需的JSON /日期不以'('和结束')/'。

Server error: HTTP status code: 500, message: There was an error deserializing the object of type System.Web.Http.Data.ChangeSetEntry[]. DateTime content '01/01/2012' does not start with '/Date(' and end with ')/' as required for JSON.

这样看来,在工具不支持的DateTime尚未。我敢肯定,我可以通过,花了一些时间想出来的,并得到它的工作,但我想我可能会觉得有点运气在这里的人谁已经修正了这个问题,并能够提供洞察力。

It would appear that the tooling doesn't support DateTime yet. I'm sure I could go through and spend a bit of time figuring it out and getting it to work, but I thought I may find a bit of luck here with someone who has already fixed this problem and can provide insight.

任何人都已经奋战呢?

更新:我加入,因为问这个,我发现更多的信息。我试着用JSON.Net我的格式化程序如下建议。我认为这将是最终的解决方案,但是,只是做如下推荐的海报是不够的。

Update: I am adding more information I have found since asking this. I tried using JSON.Net as my Formatter as suggested below. I think that will be the eventual solution, however, just doing as the poster below recommended is not enough.

在使用JSON.Net序列化,我得到以下错误:

When using the JSON.Net serializer, I get the following error:

这DataController类不支持运行'更新'实体'JObject。

This DataController does not support operation 'Update' for entity 'JObject'.

的原因是,JSON.Net不完全填充该格式化试图deserailize至(System.Web.Http.Data.ChangeSet)的对象。

The reason is that JSON.Net doesn't fully populate the object that the formatter is trying to deserailize to (System.Web.Http.Data.ChangeSet).

这是在发送的JSON是:

The json that is sent in is:

[{"Id":"0",
  "Operation":2,
  "Entity":
    {"__type":"TodoItem:#SPADateProblem.Models",
     "CreatedDate":"/Date(1325397600000-0600)/",
     "IsDone":false,
     "Title":"Blah",
     "TodoItemId":1},
  "OriginalEntity":
    {"__type":"TodoItem:#SPADateProblem.Models",
     "CreatedDate":"/Date(1325397600000-0600)/",
     "IsDone":false,
     "Title":"Blah",
     "TodoItemId":1}
}]

内置JSON中格式化能够此JSON重组与在实体和OriginalEntity领域嵌入式内的TodoItem对象变更对象。

The built in Json Formatter is able to reconstitute this Json into a ChangeSet object with embeded TodoItem objects in the Entity and OriginalEntity fields.

有没有人得到JSON.Net正确地反序列化呢?

Has anyone gotten JSON.Net to deserialize this properly?

推荐答案

现在的问题是,在目前的测试版,的ASP.NET Web API使用 DataContractJsonSerializer ,它具有良好的-known问题的DateTime 的序列化。 <一href=\"http://connect.microsoft.com/VisualStudio/feedback/details/723368/datacontractjsonserializer-does-not-properly-handle-datetime-values\"相对=nofollow>这是微软针对连接问题的一个安静的近期上调的bug; MS回应说,他们已经有一个bug跟踪这个问题,但它不会被固定在.NET 4.5 / VS11时间表。

The problem is that in the current beta, ASP.NET Web API uses DataContractJsonSerializer, which has well-known problems with serialization of DateTime. Here is a quiet recently raised bug on Microsoft Connect for the issue; MS responds that they already have a bug tracking the issue but it won't be fixed in the .Net 4.5/VS11 timeframe.

幸运的是可以替代的替代JSON序列,如詹姆斯·牛顿 - 国王优秀的 JSON.Net

Fortunately you can substitute an alternative JSON serializer, such as James Newton-King's excellent JSON.Net.

亨里克尼尔森在ASP.NET团队拥有的优秀的博客张贴展示如何使用JSON.Net用的ASP.NET Web API。这里是他实现的,它使用JSON.Net MediaTypeFormatter (它也需要被连接到的ASP.NET Web API配置,Henrik的博客显示,以及)

Henrik Nielsen on the ASP.NET team has an excellent blog post showing how you can use JSON.Net with ASP.NET Web API. Here is his implementation of a MediaTypeFormatter that uses JSON.Net (it would also need to be wired up to the ASP.NET Web API configuration, Henrik's blog demonstrates that as well).

public class JsonNetFormatter : MediaTypeFormatter
{
    private readonly JsonSerializerSettings settings;

    public JsonNetFormatter(JsonSerializerSettings settings = null)
    {
        this.settings = settings ?? new JsonSerializerSettings();

        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        Encoding = new UTF8Encoding(false, true);
    }

    protected override bool CanReadType(Type type)
    {
        return type != typeof(IKeyValueModel);
    }

    protected override bool CanWriteType(Type type)
    {
        return true;
    }

    protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
    {
        var ser = JsonSerializer.Create(settings);

        return Task.Factory.StartNew(() => {
            using (var strdr = new StreamReader(stream))
            using (var jtr = new JsonTextReader(strdr))
            {
                var deserialized = ser.Deserialize(jtr, type);
                return deserialized;
            }
        });
    }

    protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
    {
         JsonSerializer ser = JsonSerializer.Create(settings);

         return Task.Factory.StartNew(() =>
         {
              using (JsonTextWriter w = new JsonTextWriter(new StreamWriter(stream, Encoding)) { CloseOutput = false})
              {
                   ser.Serialize(w, value);
                   w.Flush();
              }
         });
    }
}    

这篇关于MVC 4单页应用和DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆