2

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 .

Ancient
  • 3,007
  • 14
  • 55
  • 104

2 Answers2

3

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));
});
Anders
  • 17,306
  • 10
  • 76
  • 144
  • see my update in question , i described my whole scenario . Hopefully now you can help me in better way . thanks – Ancient Aug 13 '13 at 10:06
  • That was a broad question :D You can still use Standard controls, but skip using Razor engine to get the data instead use Ajax to get the data. – Anders Aug 13 '13 at 11:59
0

Try with something like on JS:

function myModel(){
   var data = @(Html.Raw(Json.Encode(Model)));
   this.Name = ko.observable(data.Name);
}

Then you bind your view model:

ko.applyBindings(new myModel());
Daniele
  • 1,938
  • 16
  • 24