需要从ASP.NET MVC传递初始视图模型数据knockout.js [英] Need to pass initial viewmodel data from ASP.NET MVC to knockout.js
问题描述
我一直在寻找在knockout.js网站上的联系人编辑器示例:
I was looking at the Contacts editor sample on the knockout.js website:
<一个href=\"http://knockoutjs.com/examples/contactsEditor.html\">http://knockoutjs.com/examples/contactsEditor.html
样品完美的作品,但我需要做出两个改变它:
The sample works perfectly, but I needed to make two changes to it:
- 妙传ASP.NET MVC 3控制器的操作方法的初始数据。下面是来自服务器的code:
类
public class Phone
{
public string Type { get; set; }
public string Number { get; set; }
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Phone> Phones { get; set; }
}
样品控制器侧code
List<Phone> phoneList = new List<Phone>();
Person p1 = new Person()
{
FirstName = "Abc",
LastName = "Xyz"
};
Phone phone1 = new Phone()
{
Type = "Home",
Number = "1111111111"
};
Phone phone2 = new Phone()
{
Type = "Mobile",
Number = "1111111112"
};
phoneList.Add(phone1);
phoneList.Add(phone2);
p1.Phones = phoneList;
List<Phone> phoneList2 = new List<Phone>();
Person p2 = new Person()
{
FirstName = "Pqr",
LastName = "Stu"
};
Phone phone3 = new Phone()
{
Type = "Home",
Number = "1111111113"
};
Phone phone4 = new Phone()
{
Type = "Mobile",
Number = "1111111114"
};
phoneList2.Add(phone3);
phoneList2.Add(phone4);
p2.Phones = phoneList2;
people.Add(p1);
people.Add(p2);
ViewBag.InitialData = Json(people, JsonRequestBehavior.AllowGet);
- 除了属于视图模型的一部分的联系人的行,我还需要通过一些数据(例如ContactListName和ContactListOwner)不属于触点的行,但向视图模型本身。这些属性会显示联系人的电网之外。
我真的AP preciate如果有人能帮助我。
I would really appreciate if someone can help me with this.
推荐答案
您在您的控制器调用的的Json
方法是为了返回 JsonResult
它不会创建一个JSON字符串。你可以使用此方法从Ajax调用返回JSON。
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.
要返回一个JSON字符串到一个视图使用这样的事情。
To return a JSON string to a view use something like this.
JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewBag.InitialData = serializer.Serialize(people);
然后在您的视图code
Then in your view code
<script>
var initialData = '@Html.Raw(ViewBag.InitialData)';
....
</script>
要回答你的第二个问题。为了通过全局列表数据,比如这只是定义一个新类 ContactsList
例如
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; }
}
填充这一点,并把它传递给的JavaScriptSerializer
来代替。你会明显需要调整您的js ContactsModel
相应。
Populate this and pass this to the JavascriptSerializer
instead. You will obviously need to adjust your js ContactsModel
accordingly.
修改
下面是一个演示变化的jsfiddle需要的。
Here's a jsfiddle that demonstrates the changes needed.
http://jsfiddle.net/madcapnmckay/jRjwU/
希望这有助于。
这篇关于需要从ASP.NET MVC传递初始视图模型数据knockout.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!