通过一个JSON格式的DateTime到ASP.NET MVC [英] Pass a JSON format DateTime to ASP.NET MVC
问题描述
我们知道,在MVC格式返回日期时间为JsonResult: /日期(1240718400000)/
,我们知道如何解析它在JS
We know that MVC returns DateTime for JsonResult in this format: /Date(1240718400000)/
, and we know how to parse it in JS.
不过,这似乎MVC不接受这种方式被发送日期时间参数。例如,我有以下的动作。
However, It seems that MVC doesn't accept DateTime parameter being sent in this way. For example, I have the following Action.
[HttpGet]
public ViewResult Detail(BookDetail details) { //... }
该BookDetail类包含一个名为CREATEDATE日期时间字段,我在这个格式进行传递一个JSON对象从JS:
The BookDetail class contains a DateTime field named CreateDate, and I passed a JSON object from JS in this format:
{"CreateDate": "/Date(1319144453250)/"}
CREATEDATE被认定为无效。
CreateDate is recognized as null.
如果我用这种方式传递的JSON,它按预期工作:
If I passed the JSON in this way, it works as expected:
{"CreateDate": "2011-10-10"}
问题是,我不能改变客户端code在一个简单的方法,必须坚持/日期(1319144453250)/该格式。我不得不在服务器端的变化。
The problem is that I cannot change client side code in an easy way, have to stick to /Date(1319144453250)/ this format. I have to make changes in server side.
如何解决这个问题呢?是有关什么ModelBinder的?
How to solve this problem? Is that anything related to ModelBinder?
在此先感谢这么多!
推荐答案
的问题,因为你怀疑,是一个模型结合的问题。
The problem, as you suspected, is a model binding issue.
要解决它,创建一个自定义类型,姑且称之为 JsonDateTime
。由于DateTime的是一个结构,你不能继承它,所以创建以下类:
To work around it, create a custom type, and let's call it JsonDateTime
. Because DateTime is a struct, you cannot inherit from it, so create the following class:
public class JsonDateTime
{
public JsonDateTime(DateTime dateTime)
{
_dateTime = dateTime;
}
private DateTime _dateTime;
public DateTime Value
{
get { return _dateTime; }
set { _dateTime = value; }
}
}
更改CREATEDATE这种类型。接下来,我们需要一个自定义的模型绑定,就像这样:
Change CreateDate to this type. Next, we need a custom model binder, like so:
public class JsonDateTimeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
return new DateTime(Int64.Parse(
value.Substring(6).Replace(")/",String.Empty))); // "borrowed" from skolima's answer
}
}
然后,在Global.asax.cs中,在的Application_Start,注册您的自定义ModelBinder的:
Then, in Global.asax.cs, in Application_Start, register your custom ModelBinder:
ModelBinders.Binders.Add(typeof(JsonDateTime), new JsonDateTimeModelBinder());
这篇关于通过一个JSON格式的DateTime到ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!