I'm working on a ASP.NET MVC project and I have a controller where I am getting JSON data from an external Web API. Now I want to deserialize this JSON data and put it into a model that will eventually be passed into a Partial View.
JSON Data:
{
"results":[
{
"name":"Company A",
"providerName":"Company Provider A"
...(More Data Below)
Controller:
[HttpGet]
[Route("company-info/companyinfogetapidata")]
[AllowAnonymous]
public ActionResult CompanyInfoGetApiData(string name, int CompanyCode, string city, string state, int zip)
{
/* Json Data is fetched properly */
var json = request.Result.Content.ReadAsStringAsync().Result;
JObject o = JObject.Parse(json);
JToken ApiData = o["results"];
// Now I want to pass the JSON data into my model
CompanyResultsModel getfetcheddata = new CompanyResultsModel();
// I tried using this method below but it's not working properly
getfetcheddata = Newtonsoft.Json.JsonConvert.DeserializeObject<CompanyResultsModel>(json);
// Pass the Model containing into the PartialView Result
return PartialView(@"~/Views/Shared/companies/_companyResults.cshtml", getfetcheddata);
}
Model:
public class CompanyResultsModel
{
public string companyName { get; set; }
public string companyProvider { get; set; }
}
View:
@model Companies.CompanyResultsModel
<p>@Model.companyName</p>
<p>@Model.companyProvider</p>
After I pass in the JSON data into my model, if I use this method above for displaying the data in my view, will it return all of my data properly?
Any help is greatly appreciated!
string json = @"{ 'companyName ': 'abc', 'companyProvider': 'xyz' }";(or you need to deserialize to a model containing a propertyresultswhich isIEnumerable<CompanyResultsModel>