Reputation: 12915
I have the following in my Index.cshtml file (from the knockout site):
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
<script type="text/javascript">
// Here's my data model
var ViewModel = function (first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function () {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
</script>
My Layout has this line:
@Scripts.Render("~/bundles/knockout")
Which is configured correctly in bundler config:
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/Libraries/knockout-2.2.1.js"));
Chrome sees the file and VS is giving me intellisense, so I'm not sure what's going on. None of the knockout functions are working.
I tested this outside of MVC (just using html/css) and it worked fine. Any idea what's going on?
EDIT: I tried using a direct reference without bundler and it still doesn't work:
<script type="text/javascript" src="~/Scripts/Libraries/knockout-2.2.1.js"></script>
I'm getting an error from chrome:
Uncaught ReferenceError: ko is not defined
Upvotes: 0
Views: 3605
Reputation: 4891
I fixed my issue by removing my script line at the end of my Index.cshtml file:
<script src="~/Scripts/ConfigGroup.js"></script>
and replacing it with:
@section Scripts {
@Scripts.Render("~/Scripts/ConfigGroup.js")
}
I guess section Scripts gets loaded at a different time than includes.
Upvotes: 0
Reputation: 6839
Could you post some JS console error from chrome or firebug? Looks like a missing reference from knockout.
EDIT: Put your script at the end of its view! Another thing, the reference for knockout must stay below the reference for jquery, because its dependent.
EDIT: Register the knockout
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout-{version}.js"));
Render It in your view
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/knockout")
Upvotes: 4
Reputation: 436
Include your javascript code in a JS file and render this after knockout
Like this:
@Scripts.Render("~/bundles/knockout")
@Scripts.Render("~/bundles/MYSCRIPTS")
Upvotes: 0