jQuery dataTables编辑器插件DateTime格式问题

时间:2018-01-19 17:44:26

标签: c# jquery asp.net-mvc datetime datatables

我在网站上使用EF6 + MVC。 dataTables编辑器用于UI。一个表格中有一个字段' StartDate'。它是SQL Server中的日期时间类型。

直到我尝试编辑“开始日期”时,它才能正常工作。值。从浏览器调试中,我可以看到从后端发送到UI的JSON采用时间戳格式,即/ Date(1541923200000)/。

enter image description here

在dataTables中,我将其转换为正确的本地日期时间格式,因此它显示正确。

enter image description here

但是,我无法弄清楚如何在编辑器插件中执行此操作。它始终显示/日期(1541923200000)/。

我使用的代码是:

editorAdvertisement = new $.fn.dataTable.Editor({
    ajax: '/APN/GetAdvertisementData',

    table: "#tblAdvertisements",
    fields: [{
        label: "StartDate",
        name: "AdvStartDate"
        , type: "datetime"
        , format: 'MM\/DD\/YYYY h:mm a'
    }, {
        label: "Deadline",
        name: "AdvDeadline"
        , type: "datetime"
    }, {
        label: "TitleOfAdv",
        name: "TitleOfAdv"
    }, {
        label: "ListPrice",
        name: "ListPrice"
    }
    ]
});

var tbl = $('#tblAdvertisements').DataTable({
    pageLength: 10,
    dom: '<"html5buttons"B>lTfgitp',
    ajax: '/APN/GetAdvertisementData'
    ,
    columns: [
        {
            data: "AdvStartDate", name: "AdvStartDate"
            , type: "datetime"
                , render: function (value) {
                    var r = convertDate(value);
                    return r;
                }
            , "autoWidth": true
        },
        {
            data: "AdvDeadline", name: "AdvDeadline"
            , type: "datetime"
            , render: function (value) {
                var r = convertDate(value);
                return r;
            }
            , "autoWidth": true
        },
        { data: "TitleOfAdv", name: "TitleOfAdv", "autoWidth": true },
        {
            data: "ListPrice", name: "ListPrice", "autoWidth": true
            , render: $.fn.dataTable.render.number(',', '.', 0, '$')
        }
    ],
    order: [1, 'asc'],
    select: {
        style: 'os',
        selector: 'td:first-child'
    },
    buttons: [
        { extend: "create", editor: editorAdvertisement }
        , { extend: "edit", editor: editorAdvertisement }
        , { extend: "remove", editor: editorAdvertisement }

    ]
    , select: true
    , searching: false
    , paging: false

});

在控制器中

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult GetAdvertisementData()
{
    var request = HttpContext.Request.Form;
    var settings = Properties.Settings.Default;

    using (var db = new Database(settings.DbType, settings.DbConnection))
    {
        var response = new Editor(db, "Advertising", new[] { "AdvertisingID" })
            .TryCatch(false)
            .Model<Advertising2>()
            .Field(new Field("AdvStartDate")
                .Validator(Validation.DateFormat(
                    "MM/dd/yyyy",
                    new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
                ))
                .GetFormatter(Format.DateTime("yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy"))
                .SetFormatter(Format.DateTime("MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss"))
            )
            .Field(new Field("AdvDeadline")
                .Validator(Validation.DateFormat(
                    "MM/dd/yyyy",
                    new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
                ))
                .GetFormatter(Format.DateSqlToFormat("MM/dd/yyyy"))
                .SetFormatter(Format.DateFormatToSql("MM/dd/yyyy"))
            )

            .Field(new Field("TitleOfAdv"))
            .Field(new Field("ListPrice"))

            .Process(request)
            .Data();

        return Json(response, JsonRequestBehavior.AllowGet);
    }
}

经过长时间的搜索,我无法弄明白。有人有同样的问题吗?任何解决方案?

2 个答案:

答案 0 :(得分:1)

签出moment.js(https://momentjs.com),下载moment-with-locales.js并将其添加到BundleConfig.cs中的ScriptBundle。

然后在您的数据表的javascript代码中,您可以按正确的日期/时间格式呈现列,如下所示。注意:我的语言环境是'pt'(葡萄牙)。日期列呈现为dd / mm / yyyy hh:mm(再次,请参阅https://momentjs.com中的格式选项)。

"columns": [
        { "data": "OriginName" },
        { "data": "SmsID" },
        { "data": "DestinationNumber" },
        {
            "data": "SMSDeliveryDate",
            "render": function (data) {
                var re = /-?\d+/;
                var m = re.exec(data);
                var d = new Date(parseInt(m[0]));
                moment.locale('pt');
                var m = moment(d).format('L LTS');
                return m;
            }
        },
        { "data": "SmsStateDesc" }
    ],

希望这些信息有用。我也被困在这几个小时......

答案 1 :(得分:0)

我遇到了同样的问题,最终在Editor forum找到答案。

  

如果你看小提琴手(一个很好的工具,看看会发生什么)你   看到JSON有你得到的这种格式。如果你查看代码   视觉工作室表达并捕捉你传递给你的东西   JSON你看到类似“{12/12/2012 12:12}”的内容。实际上是   原因是JSON。

重构到第一列中的要点,它应该是这样的。

这种方法没有任何问题解决了我的问题。此版本旨在将空日期呈现为空白,否则按指示格式化。 (更新:再次重构答案,看到第二天早上格式化的代码没有按预期运行。)

{ 
   data: "AdvStartDate", 
   render: function (data, type, full) {
          if (data != null) {
                 var dtStart = new Date(parseInt(data.substr(6)));
                 return dtStart.toLocaleDateString();
          } else {
                 return "";
          }
   }