user1166905
user1166905

Reputation: 2622

ASP.Net WebApi and KO Issue with Dates

I am using EF in an ASP.Net MVC application and also using WebApi to get an element like so:

[HttpGet]
    public Student GetStudent(int id)
    {
        return db.Students.AsNoTracking().FirstOrDefault(n => n.Student_ID == id);
    }

This all works great and I map it directly into ko for use. However when I bind the value of any DateTime properties of the element i.e. date of birth I get: 1955-04-17T11:13:56. I don't want to change the web api methods or the model for every date, is there a 3rd party library or a knockout function that can handle a datetime from asp.net and correct the value for inputs.

Upvotes: 0

Views: 501

Answers (1)

Sherin Mathew
Sherin Mathew

Reputation: 1141

As Sridhar suggested in the comment. You can use moment.js to achieve this.

I've created a sample fiddle here - http://jsfiddle.net/sherin81/ordwenj6/

Knockout code

function viewModel()
{
    var self = this;
    self.dateInput = ko.observable("1955-04-17T11:13:56");
    self.formattedDate = ko.computed(function(){
        var m = moment(self.dateInput());
        return m.format("DD-MM-YYYY");
    });
}

ko.applyBindings(new viewModel());

HTML

<input data-bind="value : dateInput" />
<br/>
<span data-bind="text : formattedDate()" />

For demonstration, I've used the value from the input field for formatting. You can modify the code to use the value from the webapi and format it using moment.js.

Update

To do the same using ko custom binding handler, do the following

ko.bindingHandlers.dateFormattedByMoment = {
    update: function (element, valueAccessor, allBindingsAccessor) {
        $(element).val(moment(valueAccessor()).format("DD-MM-YYYY"));
    }
};

HTML

<input id="customBinding" data-bind="dateFormattedByMoment : dateInput()" />

Working fiddle here - http://jsfiddle.net/sherin81/ujh2cg73/

Upvotes: 1

Related Questions