我在knockout.js网站上查看了联系人编辑器示例:
@L_502_0@
该示例工作正常,但我需要对其进行两处更改:
>从ASP.NET MVC 3控制器操作方法传递初始数据.以下是服务器的代码:
类
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; } }
控制器侧代码示例
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);
>除了作为viewmodel一部分的联系人行之外,我还需要传递一些不属于联系人行但属于viewmodel本身的数据(例如ContactListName和ContactListOwner).这些属性将显示在联系人网格之外.
如果有人可以帮助我,我真的很感激.
解决方法
您在控制器中调用的Json方法是为了返回一个不创建JSON字符串的JsonResult.您将使用此方法从ajax调用返回json.
要将JSON字符串返回到视图,请使用以下内容.
JavaScriptSerializer serializer = new JavaScriptSerializer(); ViewBag.InitialData = serializer.Serialize(people);
然后在您的视图代码中
<script> var initialData = '@Html.Raw(ViewBag.InitialData)'; .... </script>
回答你的第二个问题.为了传递诸如此类的全局列表数据,只需定义一个新类ContactsList,例如
public class ContactsList { public string Name { get;set; } public string Owner { get;set; } public IList<People> People { get;set; } }
填充此内容并将其传递给JavascriptSerializer.您显然需要相应地调整您的js ContactsModel.
编辑
这是一个jsfiddle,演示了所需的更改.
http://jsfiddle.net/madcapnmckay/jRjwU/
希望这可以帮助.