Need to pass initial viewmodel data from ASP.NET MVC to knockout.js

╄→гoц情女王★ 提交于 2019-12-03 00:34:07

The Json method you are calling in your controller is meant to return a JsonResult it does not create a JSON string. You would use this method to return json from an ajax call.

To return a JSON string to a view use something like this.

JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewBag.InitialData = serializer.Serialize(people); 

Then in your view code

<script>
    var initialData = '@Html.Raw(ViewBag.InitialData)';
    ....
</script>

To answer your second question. In order to pass global list data such as this simply define a new class ContactsList e.g

public class ContactsList 
{
    public string Name { get;set; }
    public string Owner { get;set; }
    public IList<People> People { get;set; }
}

Populate this and pass this to the JavascriptSerializer instead. You will obviously need to adjust your js ContactsModel accordingly.

EDIT

Here's a jsfiddle that demonstrates the changes needed.

http://jsfiddle.net/madcapnmckay/jRjwU/

Hope this helps.

You could also use your model instead of the ViewBag:

Controller:

        public ActionResult Index()
        {
            var data= GetYourDataFromSomewhere();

            return View(data);
         }

View:

@model IEnumerable<ModelName>

....

<script type="text/javascript">
    $(document).ready(function () {

        var dataForKO = new KOViewModel(@Html.Raw(Json.Encode(Model)));

as far as the first part of the question is concerned you can try

<script>
    var initialData = '@Html.Raw(ViewBag.InitialData)'; //get the raw json
    var parsedJSON = $.parseJSON(initialData); //parse the json client side
    ko.applyBindings(new ContactsModel(parsedJSON));

</script>

the second part i really haven't understood...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!