Pass a JSON format DateTime to ASP.NET MVC

后端 未结 3 1593
不知归路
不知归路 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条回答
  •  终归单人心
    2021-02-13 13:06

    I think using custom Model Binder will do the trick. The below model binder class will work on both cases. It will parse all dot net recognizable date string as well as JSON formatted date string. No need to change any existing code.

    public class DateTimeModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = base.BindModel(controllerContext, bindingContext);
            if (model == null && (bindingContext.ModelType == typeof(DateTime) || bindingContext.ModelType == typeof(DateTime?)))
            {
                var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (value == null || String.IsNullOrEmpty(value.AttemptedValue))
                    model = (bindingContext.ModelType == typeof(DateTime?)) ? null : (object)DateTime.MinValue;
                else if (Regex.IsMatch(value.AttemptedValue, @"\/Date\(\d+\)\/"))
                    model = new DateTime(1970, 1, 1).AddMilliseconds(Int64.Parse(value.AttemptedValue.Substring(6).Replace(")/", String.Empty))).ToLocalTime();
                //else //Any other format
            }
            return model;
        }
    }
    

    Configure Model Binder in Application_Start of Global.asax

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //Your Existing Code....
    
            ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
            ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());
        }
    }
    

    Vote If it helps

提交回复
热议问题