admin管理员组

文章数量:1391964

I've got a problem when binding date value to textbox using knockout, as seen in the picture below

When the page is loaded for the first time, I'm using ajax to get the AccountStatements data.

function AccountStatementViewModel(panyID) {
    var self = this;
    ...
    var AccountStatement = {
        AccountStatementID: self.AccountStatementID,
        CompanyID: self.CompanyID,
        Description: self.Description,
        Amount: self.Amount,
        ReceiptDate: self.ReceiptDate,
        Type: self.Type
    }

    self.AccountStatement = ko.observable();
    self.AccountStatements = ko.observableArray();

    $.ajax({
        url: webroot + 'AccountStatement/GetAccountStatements',
        contentType: 'application/json; charset=utf-8',
        data: { id: self.CompanyID },
        cache: false
    }).done(function (data) {
        self.AccountStatements(data);
    });
    ...
    self.edit = function (accountStatement) {
        $('#lnkAddAccountStatement').hide('blind', 1000);
        $('#pnlAddEditAccountStatement').show('blind', 1000);
        self.AccountStatement(accountStatement);
    }
    ...
}

The Controller returns the result in json:

public JsonResult GetAccountStatements(int id)
{
    var accountStatementsVM = db.AccountStatements
        .Where(a => a.CompanyID == id)
        .Select(a => new AccountStatementViewModel
        {
            AccountStatementID = a.AccountStatementID,
            CompanyID = a.CompanyID,
            Description = a.Description,
            Amount = a.Amount,
            ReceiptDate = a.ReceiptDate,
            Type = a.Type
        })
        .ToList();

    return Json(accountStatementsVM, JsonRequestBehavior.AllowGet);
}

ant the result is:

[{"AccountStatementID":2,"CompanyID":1,"Description":"test","Amount":1000,"ReceiptDate":"/Date(1447261200000)/","Type":"Payment"}]

In the View, I display it using this code:

<tbody data-bind="foreach: AccountStatements, visible: AccountStatements().length > 0">
    <tr>
        <td data-bind="attr: { id: AccountStatementID }">
            <a href="#" class="btn btn-primary btn-xs" data-bind="click: $root.edit"><i class="glyphicon glyphicon-pencil"></i></a>
            <a href="#" class="btn btn-danger btn-xs" data-bind="click: $root.delete"><i class="glyphicon glyphicon-remove"></i></a>
        </td>
        <td data-bind="text: Description"></td>
        <td data-bind="text: Amount"></td>
        <td data-bind="date: ReceiptDate"></td>
    </tr>
</tbody>

Here is the code to format the date:

ko.bindingHandlers.date = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
        var textContent = moment(valueUnwrapped).format("DD/MM/YYYY");
        ko.bindingHandlers.text.update(element, function () { return textContent; });
    }
};

At this step, date is displayed in the right format, then if I clicked edit button, the ReceiptDate in the textbox is not formatted.

Code for ReceiptDate TextBox:

<input type="text" placeholder="Enter Receipt Date" class="form-control fdatepicker" readonly="readonly" data-bind="value: AccountStatement().ReceiptDate" />

If I change to data-bind="date: AccountStatement().ReceiptDate" the textbox will be empty.

How to format the date in the textbox?

UPDATE

I've changed the date binding handler as in this link but the ReceiptDate's TextBox value is still /Date(1447261200000)/

Changes in the view:

<input type="text" placeholder="Enter Receipt Date" class="form-control fdatepicker" readonly="readonly" data-bind="date: AccountStatement().ReceiptDate" />

and date of receipt in the table is bee empty:

<td data-bind="date: ReceiptDate"></td>

I've got a problem when binding date value to textbox using knockout, as seen in the picture below

When the page is loaded for the first time, I'm using ajax to get the AccountStatements data.

function AccountStatementViewModel(panyID) {
    var self = this;
    ...
    var AccountStatement = {
        AccountStatementID: self.AccountStatementID,
        CompanyID: self.CompanyID,
        Description: self.Description,
        Amount: self.Amount,
        ReceiptDate: self.ReceiptDate,
        Type: self.Type
    }

    self.AccountStatement = ko.observable();
    self.AccountStatements = ko.observableArray();

    $.ajax({
        url: webroot + 'AccountStatement/GetAccountStatements',
        contentType: 'application/json; charset=utf-8',
        data: { id: self.CompanyID },
        cache: false
    }).done(function (data) {
        self.AccountStatements(data);
    });
    ...
    self.edit = function (accountStatement) {
        $('#lnkAddAccountStatement').hide('blind', 1000);
        $('#pnlAddEditAccountStatement').show('blind', 1000);
        self.AccountStatement(accountStatement);
    }
    ...
}

The Controller returns the result in json:

public JsonResult GetAccountStatements(int id)
{
    var accountStatementsVM = db.AccountStatements
        .Where(a => a.CompanyID == id)
        .Select(a => new AccountStatementViewModel
        {
            AccountStatementID = a.AccountStatementID,
            CompanyID = a.CompanyID,
            Description = a.Description,
            Amount = a.Amount,
            ReceiptDate = a.ReceiptDate,
            Type = a.Type
        })
        .ToList();

    return Json(accountStatementsVM, JsonRequestBehavior.AllowGet);
}

ant the result is:

[{"AccountStatementID":2,"CompanyID":1,"Description":"test","Amount":1000,"ReceiptDate":"/Date(1447261200000)/","Type":"Payment"}]

In the View, I display it using this code:

<tbody data-bind="foreach: AccountStatements, visible: AccountStatements().length > 0">
    <tr>
        <td data-bind="attr: { id: AccountStatementID }">
            <a href="#" class="btn btn-primary btn-xs" data-bind="click: $root.edit"><i class="glyphicon glyphicon-pencil"></i></a>
            <a href="#" class="btn btn-danger btn-xs" data-bind="click: $root.delete"><i class="glyphicon glyphicon-remove"></i></a>
        </td>
        <td data-bind="text: Description"></td>
        <td data-bind="text: Amount"></td>
        <td data-bind="date: ReceiptDate"></td>
    </tr>
</tbody>

Here is the code to format the date:

ko.bindingHandlers.date = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
        var textContent = moment(valueUnwrapped).format("DD/MM/YYYY");
        ko.bindingHandlers.text.update(element, function () { return textContent; });
    }
};

At this step, date is displayed in the right format, then if I clicked edit button, the ReceiptDate in the textbox is not formatted.

Code for ReceiptDate TextBox:

<input type="text" placeholder="Enter Receipt Date" class="form-control fdatepicker" readonly="readonly" data-bind="value: AccountStatement().ReceiptDate" />

If I change to data-bind="date: AccountStatement().ReceiptDate" the textbox will be empty.

How to format the date in the textbox?

UPDATE

I've changed the date binding handler as in this link but the ReceiptDate's TextBox value is still /Date(1447261200000)/

Changes in the view:

<input type="text" placeholder="Enter Receipt Date" class="form-control fdatepicker" readonly="readonly" data-bind="date: AccountStatement().ReceiptDate" />

and date of receipt in the table is bee empty:

<td data-bind="date: ReceiptDate"></td>
Share Improve this question edited Nov 16, 2015 at 2:58 Willy asked Nov 13, 2015 at 6:59 WillyWilly 1,7297 gold badges38 silver badges82 bronze badges 7
  • something like this jsfiddle/LkqTU/27696 . cheers – super cool Commented Nov 13, 2015 at 7:28
  • @supercool thanks for the link but it doesn't work. In the link above, you have use mon date format (dd/mm/yyyy), whereas in my case, the date value is in json date format /Date(1447261200000)/. I've editted my question to supply more information. – Willy Commented Nov 13, 2015 at 8:57
  • try setting self.ReceiptDate=ko.observable(1447261200000); and check it , still it will work . moment will decode to date & format u specified . – super cool Commented Nov 13, 2015 at 9:18
  • 2 Wew, those are some major edits you've done. I've deleted my answer as the edits invalidated it as far as I could see. – Jeroen Commented Nov 13, 2015 at 9:36
  • @supercool yes it still works jsfiddle/LkqTU/27697, but in my code it doesn't work. Could you see the update section in the question? – Willy Commented Nov 13, 2015 at 9:56
 |  Show 2 more ments

2 Answers 2

Reset to default 2

Doing a custom biding is an overkill. Your custom binding is not doing anything worthy of a custom binding.

All you need is a puted observable that returns the text format of the current date.

Let's say you have this variable somewhere:

var myDate = ko.observable();

And somewhere you have code that puts some date object in it:

myDate( input ); // where input is some date object you got somehow from somewhere

Now all you need is this:

myDate.formatted = ko.pureComputed(function() {
    return moment(myDate()).format("DD/MM/YYYY");
});

Now you can just use a normal text binding:

(assuming you have myDate in the view model bound to this view)

<td data-bind="text: myDate.formatted"></td>

NOTE:

There's nothing special about myDate.formatted. If you think about it, myDate is just a function, and functions are objects so you can attach arbitrary fields to them.

It's really no different at all from creating a new variable like this:

var myFormattedDate = ko.pureComputed(function() {
    return moment(myDate()).format("DD/MM/YYYY");
});

And using it in a binding:

<td data-bind="text: myFormattedDate"></td>

In your update, $root.ReceiptDate doesn't exist. ReceiptDate is a member of the AccountStatement data. It's important to keep track of levels of context.

Your date binding will set a value, so you can't use it for something that would take a text binding (like a td in your update example).

You don't need a binding for this, you just need a formatting function, which you can use in whatever binding you choose. If you want to be able to edit the value, then you should make a writable puted based on your date value and use that in a value binding. I don't demonstrate that here.

ajaxData = [{
  "AccountStatementID": 2,
  "CompanyID": 1,
  "Description": "test",
  "Amount": 1000,
  "ReceiptDate": "/Date(1447261200000)/",
  "Type": "Payment"
}];


vm = {
  AccountStatements: ko.observableArray(ajaxData),
  formatDate: function(textValue) {
    return moment(textValue).format("DD/MM/YYYY");
  }
};

ko.applyBindings(vm);

// Add a row
setTimeout(function() {
  vm.AccountStatements.push({
    "AccountStatementID": 2,
    "CompanyID": 1,
    "Description": "test",
    "Amount": 1000,
    "ReceiptDate": "/Date(1448271200000)/",
    "Type": "Payment"
  })
}, 2500);
<script src="//cdnjs.cloudflare./ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="//maxcdn.bootstrapcdn./bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn./bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare./ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table border=1>
  <tbody data-bind="foreach: AccountStatements, visible: AccountStatements().length > 0">
    <tr>
      <td data-bind="attr: { id: AccountStatementID }"> <a href="#" class="btn btn-primary btn-xs" data-bind="click: $root.edit"><i class="glyphicon glyphicon-pencil"></i></a>
        <a href="#" class="btn btn-danger btn-xs" data-bind="click: $root.delete"><i class="glyphicon glyphicon-remove"></i></a>

      </td>
      <td data-bind="text: Description"></td>
      <td data-bind="text: Amount"></td>
      <td data-bind="text: $parent.formatDate(ReceiptDate)"></td>
      <td>
        <input type="text" class="form-control fdatepicker" readonly="readonly" data-bind="value: $parent.formatDate(ReceiptDate)" />
      </td>
    </tr>
  </tbody>
</table>

本文标签: javascriptBinding Date using KnockoutjsStack Overflow