Reputation: 1037
Good day,
I need a help in extracting JSON string and supply it on my view model.
In my example, I have a ViewModel that has 2 classes.
Classes:
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}
}
Controller:
public async Task<IActionResult> Create(IFormCollection studentInfo){
// wherein studentInfo is the key
...
}
In my controller, I'm sending this JSON string.
{[studentInfo,{"Student":{"firstname":"Johhny","lastname":"Bravo"},"Address":{"street":"New york street..."}])
I'm trying this:
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"]
}
}
But I'm having a null value
.
Any help, please?
Upvotes: 1
Views: 1934
Reputation: 1360
Try to supply directly your ViewModel in your DeserializeObject
instead of Dictionary.
var studentInfo = studentInfo["studentInfo"];
var value = JsonConvert.DeserializeObject<StudentAddressViewModel>(studentInfo);
Then call each model directly.
var studentVm = new StudentAddressViewModel{
Student = value.Student,
Address = value.Address
}
I hope this helps others as well.
Upvotes: 4