Home > Enterprise >  Map Partial Json Data to Model Class
Map Partial Json Data to Model Class

Time:03-16

I have a API Json data that contains a lot of information, but I only need to map one attribute to my model class, say Programname, I don't care of other information. I am using Json converter to DeserializeObject the API data. Is it possible to only map partial Json data to my model class? Right now, I receive error message as below if I only map one attribute of the Json data. Thanks.

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1[WebApplication2.Program]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[WebApplication2.Models.Program]'.
 public class Program
    {
        public int Prog_id { get; set; }
        public string Programname  { get; set; }
    }

Controller:

public async Task<IActionResult> Index()
        {
           
            var Client = new HttpClient();
            Client.DefaultRequestHeaders.Accept.Clear();
            Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("appllication/json"));
            HttpResponseMessage res = await Client.GetAsync("my url");
            if (res.IsSuccessStatusCode)
            {
                 var result = res.Content.ReadAsStringAsync().Result;
                List<Program> programs = JsonConvert.DeserializeObject<List<Program>>(result);
              
                return View(programs);
            }
            else
            {
                throw new Exception(res.ReasonPhrase);
            }
            
        }

View

@model IEnumerable<WebApplication2.Models.Program>
<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table >
    <thead>
        <tr> 
            <th>
              Program
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Programname)
            </td>
         
        </tr>
}
    </tbody>
</table>

CodePudding user response:

change view model to list and fix a namespace

@model List<WebApplication2.Program>

and IMHO use await instead of .Result

var result = await res.Content.ReadAsStringAsync();
List<Program> programs = JsonConvert.DeserializeObject<List<Program>>(result);
 return View(programs);

CodePudding user response:

You are getting this error because are sending a Model of type List<Program> but you need to send a Model of type IEnumerable<WebApplication2.Models.Program>. You need to send the correct Model to your View so you need to convert your List<Program> to the correct model structure before you send it to your View:

public async Task<IActionResult> Index()
{
   
    var Client = new HttpClient();
    Client.DefaultRequestHeaders.Accept.Clear();
    Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("appllication/json"));
    HttpResponseMessage res = await Client.GetAsync("my url");
    if (res.IsSuccessStatusCode)
    {
        var result = res.Content.ReadAsStringAsync().Result;
        List<Program> programs = JsonConvert.DeserializeObject<List<Program>>(result);
        //Cast your programs here to type WebApplication2.Models.Program
        var castProgram = programs.Cast<WebApplication2.Models.Program>();
        return View(castProgram);
    }
    else
    {
        throw new Exception(res.ReasonPhrase);
    }
    
}
  • Related