Handling dates with Asp.Net MVC and KnockoutJS

前端 未结 8 1183
滥情空心
滥情空心 2020-12-08 04:56

I recently started working with KnockoutJs and quickly realized using the default Json(myModelWithADate) resulted in the default json encoding of \\/Date(

相关标签:
8条回答
  • 2020-12-08 05:23

    I'm using the following code to generate short date strings. I use it for my date strings and jQueryUi Date Picker.

    class T
        {
            public DateTime d { get; set; }
        }
    
    static void Main(string[] args)
        {
            var k = new T { d = DateTime.Now };
    
            var formatter = new IsoDateTimeConverter();
            formatter.DateTimeFormat = "d";
            var s = JsonConvert.SerializeObject(k, formatter);
        }
    

    This generates the following JSON

    "{"d":"4/21/2012"}"
    

    This results clean JavaScript code for me.

    0 讨论(0)
  • 2020-12-08 05:27

    I loved Andres Toro's answer except that in my case, input fields are expecting formatted strings. So I am using JQuery to format my dates according to my favorite format provided by my helper @Html.ConvertDateFormat() Hope this helps someone day.

    var mapping = {
        'ActualDateTime': {
            update: function (options) {
                var d = /\/Date\((\d*)\)\//.exec(options.data);
                return (d) ? $.datepicker.formatDate('@Html.ConvertDateFormat()', new Date(+d[1])) : value;
                //return "5/10/2017";
            }
        }
    };
    var paymentModel = ko.mapping.fromJS(modelJSON, mapping);
    
    0 讨论(0)
提交回复
热议问题