C#-从JSON字符串结果提供ViewModel

时间:2018-07-09 03:20:26

标签: c# asp.net json asp.net-core json.net

美好的一天

我需要提取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为空。

有什么帮助吗?

1 个答案:

答案 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
}

我希望这对其他人也有帮助。