美好的一天
我需要提取JSON字符串并将其提供给我的视图模型的帮助。
在我的示例中,我有一个具有2个类的ViewModel。
课程:
public class Student {
public int StudentId {get;set;}
public string Firstname {get;set;}
public string Lastname {get;set;}
}
public class Address {
public int AddressId {get;set;}
public string Street {get;set;}
}
ViewModel:
public class StudentAddressViewModel{
public Student Student {get;set;}
public Address Address {get;set}
}
控制器:
public async Task<IActionResult> Create(IFormCollection studentInfo){
// wherein studentInfo is the key
...
}
在我的控制器中,我正在发送此JSON字符串。
{[studentInfo,{"Student":{"firstname":"Johhny","lastname":"Bravo"},"Address":{"street":"New york street..."}])
我正在尝试:
var studentInfo = studentInfo["studentInfo"];
var value = JsonConvert.DeserializeObject<Dictionary<string,string>>(studentInfo);
var studentVm = new StudentAddressViewModel{
new Student{
Firstname: value["firstname"], Lastname: value["lastname"]
},
new Address{
Address: value["address"]
}
}
但是我的value
为空。
有什么帮助吗?
答案 0 :(得分:1)
尝试直接在DeserializeObject
中提供ViewModel,而不是在Dictionary中提供。
var studentInfo = studentInfo["studentInfo"];
var value = JsonConvert.DeserializeObject<StudentAddressViewModel>(studentInfo);
然后直接调用每个模型。
var studentVm = new StudentAddressViewModel{
Student = value.Student,
Address = value.Address
}
我希望这对其他人也有帮助。