I am using Knockout with ASP.NET MVC here is my View which is populated by MVC controller
HTML
<html>
<input type="text" data-bind="value:Name" />
<script src="/Scripts/ViewModel.js"></script>
</html>
Controller
public actionresult xyz(){
var myModel = new FiestModel();
myModel.Name = "James";
return view(myModel);
}
ViewModel.Js
function mymode(){
var self = this ;
self.Name = ko.observable('@Model.Name');
}
after doing all of this when my page render my input doesn't have the specified value James
.
Update
I tell you guys about the whole scenario , in my application a user click on signup with facebook
button and facebook return user back to my xyz
action method , now i want to show the username in xyz
view . So how can i do this with api because @Anders said me to do this by Web APi .
Thanks in advance .
You shouldnt mix server side MVC and client side MVVM. Move the model population to a WebAPI controller method.
Load the data using jQuery.getJSON or other framework for Ajax You can also use ko.mapping to map the server data into ViewModels
edit: code in ViewModel.js have to be moved to the cshtml file if oyu want to use @Mode.Name, but please dont do it.
Update Something along the lines
[HttpGet]
public FiestModel xyz() {
return new FiestModel("James");
}
With mapping plugin something like
ViewModel = function(data) {
ko.mapping.fromJS(data, {}, this);
};
$.getJSON("api/myController/xyz", null, function(data) {
ko.applyBindings(new ViewModel(data));
});