Search code examples
c#.netjsonmodel-view-controllerhttpclient

Pass Nested Deserialized JSON from Controller to View


After using HttpClient class to convert my JSON to a string and deserialize it with

var response = Res.Content.ReadAsStringAsync().Result;

data = JsonConvert.DeserializeObject<List<Employee>>(response);

How do I pass the data that I receive in the Controller from the call using the Model below to the View?

        public class RuleType
        {
            public int Id { get; set; }
            public string Description { get; set; }
            public bool Inactive { get; set; }
        }

        public class RuleCategory
        {
            public int Id { get; set; }
            public string Description { get; set; }
            public bool Inactive { get; set; }
        }

        public class Employee
        {
            public string Description { get; set; }
            public object EndDateTime { get; set; }
            public int Id { get; set; }
            public bool Inactive { get; set; }
            public int RuleAction { get; set; }
            public DateTime StartDateTime { get; set; }
            public RuleType RuleType { get; set; }
            public RuleCategory RuleCategory { get; set; }
        }

Here is one object from the call

[
    {
        "Description": "Test Description",
        "EndDateTime": null,
        "Id": 1,
        "Inactive": false,
        "RuleAction": -2,
        "StartDateTime": "2017-01-06T14:58:58Z",
        "RuleType": {
            "Id": 6,
            "Description": "Test Description",
            "Inactive": false
        },
        "RuleCategory": {
            "Id": 1,
            "Description": "Description",
            "Inactive": false
        }
    }
]

Solution

  • Not sure if I'm missing something, but if you have an object you want to return to the view from the controller, you simply:

    return View(viewModel); // in your case viewModel = 'data'