s

knockout dynamically bind image src based on boolean value edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 04 February 2021 | 1788

In my asp .net mvc application in the razor view I want to bind img src attribute based on weather IsFavourite is true of false. I am setting up the initial value of observable isFavourite by setting the value from asp .net mvc model @(@Model.IsFavourite == true ? "true" : "false"). Check the code below how this can be done.

<img data-bind="attr:{src: viewModel.isFavourite() ? '/Content/images/favourite_active.png' : '/Content/images/favourite.png'}"  />


Javascript

var viewModel = {
    isFavourite: ko.observable(@(@Model.IsFavourite == true ? "true" : "false")),
};
ko.applyBindings(viewModel);