knockout dates being reset on post to mvc controller

后端 未结 3 1609
甜味超标
甜味超标 2021-01-20 23:15

I have a knockout/mvc3 application. I am passing the date back to a controller.

controller

public ActionResult PackageUpdate(Package upd         


        
3条回答
  •  孤城傲影
    2021-01-20 23:54

    Thanks to Matt Johnson I was able to change the way the dates were being sent to the browser. It was a relativly easy fix taken from Perishable Dave answer to a similar problem with ASP.NET MVC JsonResult Date Format

    My JsonNetResult class now look like

    public class JsonNetResult : ActionResult
    {
        private const string _dateFormat = "yyyy-MM-dd hh:mm:ss";
    
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        public object Data { get; set; }
    
        public JsonSerializerSettings SerializerSettings { get; set; }
        public Formatting Formatting { get; set; }
    
        public JsonNetResult()
        {
            SerializerSettings = new JsonSerializerSettings();
            Formatting = Formatting.Indented;
            SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
        }
    
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
    
            HttpResponseBase response = context.HttpContext.Response;
    
            response.ContentType = !string.IsNullOrEmpty(ContentType)
              ? ContentType
              : "application/json";
    
            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;
    
            if (Data != null)
            {
                var isoConvert = new IsoDateTimeConverter();
                isoConvert.DateTimeFormat = _dateFormat;
    
                JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
    
                JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
                serializer.Converters.Add(isoConvert);
    
                serializer.Serialize(writer, Data);
    
                writer.Flush();
            }
        }
    }
    

    I have added the iso date converter to the serizer

    in the controller you invoke it by:

    public JsonNetResult YourAction(){
        //your logic here
        return JsonNetResult(/*your object here*/);
    }
    

    When I wrote this I did not know about Web API. It is worth a look as it will do a lot of the heavy lifting when it comes to serialization of your objects. Checkout Getting Started with ASP.NET Web API 2

提交回复
热议问题