Handling dates with Asp.Net MVC and KnockoutJS

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

    I always use a data converter instead of sending data directly to server to fix any client encoding or parsing issues, without the need to use additional tools.

    In the Knockout JS view model file, I add the following code before the view model setup, which intercept selected proeprries of the view model and use moment.js to take care of date convertions:

    // converting data before sending to controller
    var dataConverter = function (key, value) {  
        if (key === 'InvoiceDate') {
            return moment(value).format("YYYY MMMM DD");
        }
    
        return value;
    };
    

    Then I use the dataConverter instead of data in the ajax save method within the view model:

    // Example view model for sales invoice
    SalesInvoiceViewModel = function (data) {
        var self = this;
        ko.mapping.fromJS(data, {}, self);
        self.SaveInvoice = function () {
            $.ajax({
                url: '/SalesInvoices/SaveInvoice/',
                type: 'POST',
                data: ko.toJSON(self, **dataConverter**),
                contentType: 'application/json',
                success: function (data) {
                    if (data.invoiceViewModel !== null) {
                        ko.mapping.fromJS(data.invoiceViewModel, {}, self);
                    }
                    if (data.redirectToLocation !== null) {
                        window.location = data.redirectToLocation;
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    // report error to user
                }
            });
        }
    

提交回复
热议问题