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?
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.
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)
In My scenario @RobVious answer was part but not completed. I followed these steps to the solution.
Add below sections into header <head>
of shared layout (ex _Layout.cshtml)
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/knockout")
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());
});
if this won't work check whether you knockout.js is loading or not like below using inspect elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With