Pass a JSON format DateTime to ASP.NET MVC

后端 未结 3 1606
不知归路
不知归路 2021-02-13 12:17

We know that MVC returns DateTime for JsonResult in this format: /Date(1240718400000)/, and we know how to parse it in JS.

However, It seems that MVC doesn\

3条回答
  •  Happy的楠姐
    2021-02-13 13:11

    The problem, as you suspected, is a model binding issue.

    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; }
        }
    }
    

    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
        }
    }
    

    Then, in Global.asax.cs, in Application_Start, register your custom ModelBinder:

    ModelBinders.Binders.Add(typeof(JsonDateTime), new JsonDateTimeModelBinder());
    

提交回复
热议问题