Handling dates with Asp.Net MVC and KnockoutJS

前端 未结 8 1181
滥情空心
滥情空心 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:10

    Just came up on this question because we also started using knockout.js on our MVC3 app. Since we already have jQuery datepicker and we need to format dates differently by locale (portal has different languages and different formats are presented per language), so maybe this mashup of technological requirements arise somewhere else and will be useful:

    var jsDateFormat = "@CultureHelper.JsDateFormat"; // can be something like yy-mm-dd
    
    //...
    
     ko.bindingHandlers.date = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var value = valueAccessor();
            if (value != null) {
                var jsonDate = new Date(parseInt(valueAccessor().substr(6)));
                element.innerHTML = jQuery.datepicker.formatDate(jsDateFormat, jsonDate);
            }
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        }
    };
    

    And in the view then for example:

    :

提交回复
热议问题