我在这里看到的问题和答案有点类似于我的问题,但它们要么比我的实现更先进,要么是不同的方向。
问题是,接收一个包含嵌套信息的 json 字符串,如下所示:
{"StudentBaseData":{
"StudentGuid":123456,
"FirstName":"my name",
"LastName":"my last name",
"Email":"email@email.com",
"Password":123456,
"Birthdate":"01-01-1986",
"Picture":null,
"MobilePhone":"123456789",
"Gender":"Hr."},
"PrimaryEducation":{
"Name":"something",
"Institution":"something",
"StudyStartDate":"2011-12-01",
"GraduationDate":"2013-12-01",
"ThesisSubject":"something"},
"MAddress":{
"Street":"a road",
"StreetNr":"12",
"ZipCode":"1234",
"City":"a city"}
}
我可以将其重新打包为我可以理解的视图模型(我的淘汰技能非常基础,我只是在学习这个),但问题是当我必须将视图模型发送回后端时。这是一个网络API。Web api 期望返回相同类型的 json。
这是我当前的视图模型:
var ViewModel = {
studentGuid: ko.observable("<%=Session["guid"]%>"),
firstname: ko.observable(""),
lastname: ko.observable(""),
email: ko.observable(""),
password: ko.observable(""),
birthdate: ko.observable(""),
day: ko.observable(""),
month: ko.observable(""),
year: ko.observable(""),
picture: ko.observable(""),
mobilephone: ko.observable(""),
gender: ko.observable(""),
street: ko.observable(""),
streetnr: ko.observable(""),
zipcode: ko.observable(""),
city: ko.observable(""),
primaryEducationName: ko.observable(""),
primaryEducationInstitution: ko.observable(""),
primaryEducationStudyStartDate: ko.observable(""),
primaryEducationGraduationDate: ko.observable(""),
primaryEducationThesisSubject: ko.observable("")
};
就像我说的,简单。但问题是如何复制嵌套。在 viewmodel 中像这样进行 observables 是行不通的:
StudentBaseData.firstname: ko.observable(""),
StudentBaseData.lastname: ko.observable(""),
StudentBaseData.email: ko.observable(""),
这也不是:
"StudentBaseData.firstname": ko.observable(""),
"StudentBaseData.lastname": ko.observable(""),
"StudentBaseData.email": ko.observable(""),
然后我看到了类似的东西:
StudentBaseData[
lastname: ko.observable(""),
email": ko.observable("")
]
那也行不通。
我该怎么办?