我有一个控制器动作,它有效地简单地返回模型的JsonResult。所以,在我的方法中,我有如下内容:
return new JsonResult(myModel);
这很有效,除了一个问题。在模型中有一个日期属性,这似乎在Json结果中返回,如下所示:
"\/Date(1239018869048)\/"
我应该如何处理日期,以便它们以我所需的格式返回?或者我如何处理脚本上面的这种格式?
我有一个控制器动作,它有效地简单地返回模型的JsonResult。所以,在我的方法中,我有如下内容:
return new JsonResult(myModel);
这很有效,除了一个问题。在模型中有一个日期属性,这似乎在Json结果中返回,如下所示:
"\/Date(1239018869048)\/"
我应该如何处理日期,以便它们以我所需的格式返回?或者我如何处理脚本上面的这种格式?
当前回答
使用jQuery自动转换日期$.parseJSON
注意:这个答案提供了一个jQuery扩展,添加了自动ISO和.net日期格式支持。
因为你使用Asp.net MVC,我怀疑你在客户端使用jQuery。我建议你阅读这篇有代码如何使用$的博客文章。parseJSON自动转换日期。
代码支持Asp.net格式的日期,就像你提到的,以及ISO格式的日期。所有日期都将使用$. parsejson()自动格式化。
其他回答
你可以使用这个方法:
String.prototype.jsonToDate = function(){
try{
var date;
eval(("date = new " + this).replace(/\//g,''));
return date;
}
catch(e){
return new Date(0);
}
};
我有同样的问题,而不是返回实际的日期值,我只是使用ToString(“dd MMM yyyy”)。然后在我的javascript中,我使用了新的日期(datevalue),其中datevalue可能是“01 Jan 2009”。
客户端有很多解决方案,但是如果您愿意,可以更改输出服务器端。
有一些方法可以解决这个问题,我将从基本的开始。您必须创建JsonResult类的子类,并重写ExecuteResult方法。在此基础上,您可以采用几种不同的方法来更改序列化。
方法1: 默认实现使用JsonScriptSerializer。如果查看文档,可以使用RegisterConverters方法添加自定义JavaScriptConverters。但是有一些问题:JavaScriptConverter序列化到一个字典,也就是它接受一个对象并序列化到一个Json字典。为了使对象序列化为字符串,它需要一点技巧,请参阅post。这个特殊的hack也将转义字符串。
public class CustomJsonResult : JsonResult
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Use your custom JavaScriptConverter subclass here.
serializer.RegisterConverters(new JavascriptConverter[] { new CustomConverter });
response.Write(serializer.Serialize(Data));
}
}
}
方法二(推荐): 第二种方法是从重写的JsonResult开始,然后使用另一个Json序列化器,在我的例子中是Json。净序列化器。这并不需要方法1的技巧。这是我的JsonResult子类的实现:
public class CustomJsonResult : JsonResult
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
// Using Json.NET serializer
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(Data, isoConvert));
}
}
}
使用的例子:
[HttpGet]
public ActionResult Index() {
return new CustomJsonResult { Data = new { users=db.Users.ToList(); } };
}
额外的学分: 詹姆斯Newton-King
Ajax communication between the client and the server often involves data in JSON format. While JSON works well for strings, numbers and Booleans it can pose some difficulties for dates due to the way ASP.NET serializes them. As it doesn't have any special representation for dates, they are serialized as plain strings. As a solution the default serialization mechanism of ASP.NET Web Forms and MVC serializes dates in a special form - /Date(ticks)/- where ticks is the number of milliseconds since 1 January 1970.
这个问题有两种解决方法:
客户端
将接收到的日期字符串转换为数字,并使用日期类的构造函数以tick为参数创建日期对象。
function ToJavaScriptDate(value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
服务器端
前面的解决方案使用客户端脚本将日期转换为JavaScript date对象。您还可以使用服务器端代码以您选择的格式序列化. net DateTime实例。 要完成这个任务,你需要创建自己的ActionResult,然后以你想要的方式序列化数据。
参考: http://www.developer.com/net/dealing-with-json-dates-in-asp.net-mvc.html
最简单的一个:
var milisegundos = parseInt(data.replace(“/Date(”, “”).replace(“)/”, “”)); Var newDate = new Date(milisegundos).toLocaleDateString("en-UE");