Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ko.applyBindings gives error "ko is not defined" when using ko in view

I have the following in my MVC Layout (at the bottom):

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/knockout")
@Scripts.Render("~/bundles/viewmodels")

I see knockout loading in my Sources tab in Developer tools.

In one of my views, I have to do the following:

<script type="text/javascript">ko.applyBindings(@Html.Raw(Json.Encode(Model)));</script>

But this gives me an error: ko is not defined

Why is this happening, despite knockout being loaded?

like image 326
RobVious Avatar asked Sep 17 '13 01:09

RobVious


3 Answers

The problem was that my view was loading before knockout. Pushing this up to the top of my Layout.cshtml:

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

Fixed the problem.

like image 93
RobVious Avatar answered Sep 22 '22 10:09

RobVious


you should put @ko.Apply(Model) at bottom of page too, instead of pull scripts on top of page.

The following code will solve your problem

@section scripts{
    @ko.Apply(Model)
}

Remember to declare a scripts section on layout view, otherwise will cause a exception

@RenderSection("scripts", required: false)
like image 44
Diego Mendes Avatar answered Sep 25 '22 10:09

Diego Mendes


In My scenario @RobVious answer was part but not completed. I followed these steps to the solution.

  1. Add below sections into header <head> of shared layout (ex _Layout.cshtml)

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

  2. Then Add knockout code to document ready tag like below.

    $(document).ready(function () { function AppViewModel() { this.firstName = "Bert"; this.lastName = "Bertington"; } ko.applyBindings(new AppViewModel()); });

  3. if this won't work check whether you knockout.js is loading or not like below using inspect elements enter image description here

like image 38
Menuka Ishan Avatar answered Sep 25 '22 10:09

Menuka Ishan