将JSON格式DateTime传递给ASP.NET MVC

tsh*_*hao 13 asp.net-mvc json

我们知道MVC以这种格式返回JsonResult的DateTime:,/Date(1240718400000)/我们知道如何在JS中解析它.

但是,似乎MVC不接受以这种方式发送的DateTime参数.例如,我有以下Action.

[HttpGet]
public ViewResult Detail(BookDetail details) { //... }
Run Code Online (Sandbox Code Playgroud)

BookDetail类包含一个名为CreateDate的DateTime字段,我以这种格式从JS传递了一个JSON对象:

{"CreateDate": "/Date(1319144453250)/"}
Run Code Online (Sandbox Code Playgroud)

CreateDate被识别为null.

如果我以这种方式传递JSON,它按预期工作:

{"CreateDate": "2011-10-10"}
Run Code Online (Sandbox Code Playgroud)

问题是我无法以简单的方式更改客户端代码,必须坚持/ Date(1319144453250)/这种格式.我必须在服务器端进行更改.

如何解决这个问题呢?这与ModelBinder有关吗?

非常感谢提前!

cou*_*ben 7

您怀疑,问题是模型绑定问题.

要解决它,请创建一个自定义类型,然后调用它JsonDateTime.因为DateTime是一个结构,所以不能从它继承,所以创建以下类:

public class JsonDateTime
{
    public JsonDateTime(DateTime dateTime)
    {
        _dateTime = dateTime;
    }

    private DateTime _dateTime;

    public DateTime Value
    {
        get { return _dateTime; }
        set { _dateTime = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

将CreateDate更改为此类型.接下来,我们需要一个自定义模型绑定器,如下所示:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在Global.asax.cs中,在Application_Start中,注册您的自定义ModelBinder:

ModelBinders.Binders.Add(typeof(JsonDateTime), new JsonDateTimeModelBinder());
Run Code Online (Sandbox Code Playgroud)

  • 为什么要创建包装器对象JsonDateTime?你提到'...因为DateTime是一个结构,你不能继承它',但我看到这里没有使用继承. (2认同)