Damkulul
Damkulul

Reputation: 1476

Why ASP.NET MVC doesn't recognize knockout

I am trying to use knockout.js in my MVC 4 (Web Api) project, so I added Knockout.js using Managae NuGet Packages, than I added it to the BundleConfig

 bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                    "~/Scripts/knockout-{version}.js"));

I added it in my _Layout.cshtml

 @Scripts.Render("~/bundles/knockout")

When I tried to use it in my ViewModel.js - ko.applyBindings(new ViewModel()); it didn't recognize it -> the "word" ko wasn't found...I ignored it and continued to write my code but after running it no comment from the knockout.. What am I missing here?

Upvotes: 0

Views: 507

Answers (1)

JotaBe
JotaBe

Reputation: 39004

You have not shown your code, but I think the problem is quite easy to explain:

  • by default, MVC renders the bundles in the Scripts section, which is near the bottom of the page
  • I bet that you're calling the knockout method inside your templates body. What happens is that, at that point, the Scripts are still not included in the page, thus the error message

You have to change your code, so that, when you call one of the ko method, ko is already loaded. Two possible options (but there are more):

  • render the KO bundle on the <head>section of your layout
  • call the ko function from inside the jQuery document ready event, like this:

    $(document).ready(function() { // Your ko calls here });

In fact, the second solution wait to execute the code until all the page has been loaded, and is the recommende way to run any script that interacts with the DOM of the page.

Upvotes: 1

Related Questions