I'm trying to implement knockoutjs and requirejs to my asp.net mvc app.
So, here's what I have.
Views/Shared/_Layout.cshtml
<html>
<body>
@RenderBody()
<script src="~/Scripts/require.js" data-main="/Scripts/app/main"></script>
@RenderSection("scripts", required: false)
</body>
<html>
Scripts/main.js
require.config({
baseUrl: '/Scripts',
paths: {
ko: '/Scripts/knockout-3.3.0'
}
});
Views/Product/Index.cshtml (one of my views)
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: products">
<tr>
<td data-bind="text: $data.product"></td>
</tr>
</tbody>
</table>
<script src="~/Scripts/app/product.js"></script>
@section scripts {
// Some scripts here
}
Scripts/app/product.js
define(['ko'], function (ko) {
var data = [
{ name: 'Product1' },
{ name: 'Product2' }
];
var Product = function () {
this.name = ko.observable()
};
var productVm = {
products: ko.observableArray([]),
load: function() {
for (var i = 0; i < data.length; i++) {
productVm.products.push(new Product()
.name(data[i].name));
}
}
}
productVm.load();
ko.applyBindings(productVm);
});
Just in case you need to see my folder structure
Solution
- Scripts
-- app
--- product.js
-- require.js
-- knockout-3.3.0.js
- Views
-- Product
--- Index.cshtml
-- Shared
--- _Layout.cshtml
Then, once I navigate to my products index page. I got a define is not define
error. What am I missing?