itzmebibin
itzmebibin

Reputation: 9439

Image path binding in MVC using knockoutjs

I wants to display an image in my MVC application using knockoutjs. I am using the following code. Javascript (images.js)

 function viewModel() {
        this.ImgPath = ko.observable("~/Content/Images/abcd.JPG");
};
ko.applyBindings(new viewModel());

in View,

<img data-bind="attr: { src: ImgPath }" />

Also I added the following in my view.

<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/knockout-3.3.0.js"></script>
<script src="~/Scripts/images.js"></script>

But image is not displaying in my application. How to bind the image path to view in mvc using knockout?

Upvotes: 0

Views: 785

Answers (2)

ramiramilu
ramiramilu

Reputation: 17182

Change image path from "~/Content/Images/abcd.JPG" to "/Content/Images/abcd.JPG".

~ will not be understood by HTML and it will not load image. ~ will only be understood by ASP.Net engine.

Upvotes: 3

itzmebibin
itzmebibin

Reputation: 9439

I made a small change in my code.

function viewModel() {
this.ImgPath = ko.observable("/Content/Images/abcd.JPG");
};
ko.applyBindings(new viewModel());

And now its working fine. Thanks to all.

Upvotes: 1

Related Questions