【问题标题】:Return Json from MVC controller but Date format not proper in javascript从 MVC 控制器返回 Json,但日期格式在 javascript 中不正确
【发布时间】:2012-02-29 18:51:06
【问题描述】:

我在一个项目中工作,我使用数据库中的数据创建一个网格,在我的控制器中我有这个代码

List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord();

它返回给我一些日期的员工列表,然后我使用 return Json(list); 进一步将其转换为 Json; 但是我在我的 java 脚本网格中得到的日期格式像 /Date(1325075075113)/ 我的 javascript 代码就像

$.ajax({
        url: ../getRecord,
        type: 'POST',
        data: {},
        async: false,
        success: function (result) {
            if (result !== "") {
                       Create Grid     
                        }
                    }
                });

【问题讨论】:

  • 最后我解决了我的问题, List list = new Employee(connectionString).GetEmployeeRecord(); return Json(list.Select(n => new { n.key1, AdditionalOn = n.AddedOn.Value.ToShortDateString() : String.Empty, n.key2, n.key3 }));

标签: c# javascript jquery asp.net-mvc-3


【解决方案1】:

我为这种场景创建了两个扩展方法

/// <summary>
/// Converts the value of the current System.DateTime object to its equivalent string representation using the specified format and culture-specific format information.
/// </summary>
/// <param name="date">DateTime instance</param>
/// <param name="format">A standard or custom date and time format string.</param>
/// <returns>A string representation of value of the current System.DateTime object as specified by format and provider.</returns>
public static string ToFormatString(this DateTime date, string format) {
    return date.ToString(format, new CultureInfo("en-US"));
}

/// <summary>
/// Returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
/// </summary>
/// <param name="dt">Date Time</param>
/// <returns>Returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)</returns>
public static double UnixTicks(this DateTime dt) {
    DateTime d1 = new DateTime(1970, 1, 1);
    DateTime d2 = dt.ToUniversalTime();
    TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
    return ts.TotalMilliseconds;
}

您可以选择其中任何一个。要将日期转换为字符串,您只需这样做,

 var dateString = myDate.ToFormatString("dd/MM/yyyy");

您不必担心机器的文化。

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    它不是 javascript 问题,我认为您需要按照您的要求在代码中格式化您的日期,即仅在 C# 代码中。

    以下内容可能对您有所帮助..

    List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord();
    list.All(x => { x.mydate = x.mydate.ToString("dd/MM/yyyy"); return true; }) 
    

    当您的属性为 datetime 类型时尝试此解决方案,因为在第一个解决方案中,如果属性类型为 datetime,则会给您一个错误

    var q = from o in MyList
            select new { mydate   = x.mydate.ToString("dd/MM/yyyy"), 
                         prop1 = o.prop1, 
                         prop2 = o.prop2
                       };
    

    【讨论】:

    • 是的,我的属性是日期时间类型,它也可以为空。我还面临同样的问题。我试过 DateTimeFormatInfo dtfi = new DateTimeFormatInfo(); dtfi.ShortDatePattern = "MM-dd-yyyy"; list.ForEach(f => f.AddedOn = Convert.ToDateTime(f.AddedOn, dtfi));和你的一样。
    【解决方案3】:

    是的,这是服务器端(生成)问题。 Employee 实体中日期属性的类型是什么。默认行为调用其 ToString() 方法。

    【讨论】:

      【解决方案4】:

      我用这种方式做了这样的事情:

      将网格放入-partial view 中。 从您的控制器返回 json 返回部分视图:

        List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord();
        return PartialView("GridPartial", list);
      

      在您看来: 1.使用:@model IEnumerable. 2.添加一个包含部分的div:

        <div id="partial">
           @Html.Partial("GridPartial", @model)         
        </div> 
      

      然后在你的 ajax 中:

      $.ajax({
              url: ../getRecord,
              type: 'POST',
              data: {},
              async: false,
              success: function (result) {
                     if (result.indexOf("<!DOCTYPE html>") == -1) {
                            $("#partial").empty();
                            $("#partial").html(result);
                        }
                          }
                      });
      

      在模型(你的列表)的局部视图中foreach并填充网格...

      【讨论】:

        【解决方案5】:

        .Net 使用的 JavascriptSerializer 生成特定的日期格式。

        如果你想在客户端格式化它,你可以将它转换为 JavaScript 日期:

        var javascriptDate = new Date(parseInt(dateTimeInNetFormat.substr(6)))
        

        【讨论】:

          【解决方案6】:

          我已经通过以下方式为自己解决了这个问题:

          只需添加到 IEmployeeEntity 1 个额外的文件,它将根据需要格式化此 DateTime,然后在回调中使用它。

          class IEmployeeEntity
          {
             public DateTime StartDate {set; get;}
          
             public DateTime FormatedStartDate {  get  { return StartDate.ToString("MM/dd/yyyy") } }
          
          }
          

          因此,只需在您的 Javascript 中使用 FormatedStartDate 即可获得正确的格式。

          或者如果你有一些视图类,你只需这样做

          class IEmployeeEntity
          {
             private DateTime startDate;
             public DateTime StartDate 
             { 
                 set 
                    { 
                        startDate = value; 
                    } 
                 get { 
                        return startDate.ToString("MM/dd/yyyy"); 
                     } 
              }
          }
          

          【讨论】:

            【解决方案7】:

            我通过以下方式解决了我的问题

            List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord(); 
                    return Json(
                      list.Select(
                              n => new { 
                              n.key1, 
                              AddedOn = n.AddedOn.Value.ToShortDateString() : String.Empty, 
                              n.key2, n.key3 
                    }));
            

            【讨论】:

              【解决方案8】:

              它返回服务器端日期格式。您需要定义自己的函数来更改日期格式。

              function jsonDateFormat(jsonServerDate) {
              
              // Changed data format;
              return (new Date(parseInt(jsonServerDate.substr(6)))).format("mm-dd-yyyy / h:MM tt");
              

              };

              【讨论】:

                猜你喜欢
                • 2014-04-10
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-12-06
                • 2019-01-03
                • 2020-03-19
                相关资源
                最近更新 更多