Retrieve JSON data from a web API and transmit it to a partial view using a controller

Currently, my code is set up like this:

 public ActionResult Search(SearchModel model)
    {
        string url = "http://10.0.2.31/testwebapi/api/data";
        WebClient wc = new WebClient();

        wc.QueryString.Add("forename", model.Forename);
        wc.QueryString.Add("surname", model.Surname);
        wc.QueryString.Add("caseid", model.CaseId);
        wc.QueryString.Add("postcode", model.Postcode);
        wc.QueryString.Add("telephone", model.Telephone);
        wc.QueryString.Add("email", model.Email);
        wc.QueryString.Add("title", model.Title);

        var data = wc.UploadValues(url, "POST", wc.QueryString);


        var responseString = Encoding.Default.GetString(data);

        return PartialView("~/Views/Shared/SearchResults.cshtml", responseString);

    }

    public class RootObject
    {
        public int Caseid { get; set; }
        public string Title { get; set; }
        public string Forename { get; set; }
        public string Surname { get; set; }
        public string Postcode { get; set; }
        public string Telephone { get; set; }
        public string Email { get; set; }
        public string DOB { get; set; }
        public string Mobile { get; set; }
        public string MaritalStatus { get; set; }
        public string LoanPurpose { get; set; }
        public bool CourtesyCall { get; set; }
        public string isOpen { get; set; }
    }

I am struggling to figure out why it's not pulling the JSON data from the web api correctly. My intention is to pass that data to a PartialView where I can iterate over it with a @foreach loop and display it in a table format.

This is how the current output looks like:

https://i.stack.imgur.com/w5ghx.png

@model  string
@{ 
    Layout = null;
}

@foreach(var Case in Model)
{
    <p>@Case</p>
}

Partial view code snippet.

This is the updated version of my partial view:

@model  IEnumerable<Savvy_CRM_MVC.Models.RootObject>
@{ 
    Layout = null;
}

@foreach (var m in Model)
{
    <p>@m</p>
}

Despite updating the for each loop, the output still displays as Savvy_CRM_MVC.Models.RootObject instead of the actual data

Answer №1

The issue lies in binding your model directly to the raw JSON string.

To solve this, you should deserialize the JSON string into your RootObject class and use RootObject as the model for your view.

Here is an example code snippet using Newtonsoft JSON.net to deserialize the string:

var rootObjects = JsonConvert.DeserializeObject<RootObject[]>(responseString);
return PartialView("~/Views/Shared/SearchResults.cshtml", rootObjects);

Remember to update your view with the following:

@model IEnumerable<RootObject>

Additionally, make sure to adjust your view to properly display the properties of your model.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unfolding the potential of variables in JSON.stringify with Node.js

I am currently developing a node.js API for my app, which includes a simple TCP server that accepts NDJSON (newline delimited JSON). However, I have encountered an issue with the JSON stringify method. The problem arises when I attempt to expand all variab ...

Processing JSON data in django view

I am looking to integrate the api that I have created using django_rest_framework into my API. I need to utilize the JSON data produced in both my views and templates. The JSON data structure looks like this - [ { "url": "http://127.0.0.1:8000/app/clubs/ ...

Utilizing Python requests for retrieving dynamic website data

Currently, I am utilizing Python (BeautifulSoup) to extract data from various websites. However, there are instances where accessing search results can be challenging. For example: import requests from bs4 import BeautifulSoup url1 = 'https://auto.r ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

Login block for Episerver

I'm brand new to episerver cms and I'm trying to add a "login block" to the top right corner of my home page where front-end users can log in. I've created a “LoginBlock”, ”LoginBlockController” along with a class called “LoginForm ...

There is an issue with decoding JSON in the Flask API response using Python

I created a basic Python API with flask, and this is what my response looks like... response = { "id" : "345345d", "topdata" : { "top" : 234, "left" : 42, }, "bottomdata" : { "color" : "red", "bg" : "bl ...

NodeJS JSON file write function not updating as expected

I'm working on a task that involves reading an existing JSON file, updating the value within it, and then saving it back. However, I've encountered the following error message: node:internal/modules/cjs/loader:944 throw err; ^ Error: Cannot ...

When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days: I have data in a model that indicates the available amount of free pallets ...

Transferring information from JSON to HTML

Recently, I came across this handy design tool within our service that helps generate Gauge charts by simply adding a specific div class to the desired pages. <div class="gauge" id="g0" data-settings=' { "value": ...

Sending response from controller to AJAX jQuery

I am working with ASP.net MVC and I am receiving an "Error" from my JavaScript code below: Here is the AJAX jQuery code snippet: $(document).ready(function () { var dataId; $(".item2 .small-img").click(function () { dataId = $ ...

What is the best way to merge strings and JMESPath queries in order to construct a webhook payload?

I'm currently exploring the use of Cloud Custodian webhooks to generate tagged events in Datadog using the Datadog API. The code snippet below is almost functional, however, the tag for account_id is not being created in Datadog. When examining the b ...

The issue with the localhost route not functioning properly lies in the failure to return the expected JSON response upon

Hey fellow developers, I have encountered an issue with my async Get() method. It successfully reads Json data, but when I try to access the route -> localhost:59185/api/encompass/data, I get the following message: No HTTP resource was found that matche ...

Error code 0 occurs in jQuery AJAX when there is an issue with the communication between the client

Currently delving into the world of ASP.NET and wanted to create a basic website utilizing ajax to retrieve a simple string from the server. Upon running the ajax request, an error message pops up stating An error occurred: 0 error Here's a glimpse ...

Use Picasso to loop through and display images within an image set

Here is a sample of my .json file: { "0": { "image_path": "192.168.1.52/test/image/im1.jpg", "title": "image 1" }, "1": { "image_path": "192.168.1.52/test/image/im2.jpg", "title": ...

What is the reason behind postgres' error message: "operator does not exist: json ? unknown

Trying to execute this specific query against my postgres database, I encountered a challenge: select distinct offer_id from offers where listing_id = 2299392 group by offer_id having not bool_or(status in ('Rejected', 'Draft&ap ...

The jq tool encounters issues with parsing invalid JSON, specifically with numeric values that are separated by spaces

It appears to be invalid as JSON format, however the jq command does not raise an error and is able to parse it successfully. What could be the reason for this behavior? $ echo '1 2 3' | jq . 1 2 3 (Version: jq-1.5) ...

None of the Views are rendered after executing RedirectToAction

I created a Login Page that redirects to the required page after validation. However, when it redirects, the previous Login page view appears instead of the expected view. Below is the JavaScript code I am using: function abc() { var email = ...

Unable to render the JSON data that was retrieved from a jQuery AJAX request

I am having trouble displaying JSON data that is returned from an AJAX call. Can someone please assist me? I am new to this. $.ajaxSetup({ cache: false, timeout: 5000 }); //String.prototype.toJSON; var the_object = {}; function concatObject(obj) { ...

If the given response `resp` can be parsed as JSON, then the function `$

I was using this script to check if the server's response data is in JSON format: try { json = $.parseJSON(resp); } catch (error) { json = null; } if (json) { // } else { // } However, I noticed that it returns true when 'res ...

Rendering json data in jquery

Is there a way to load a .json file from the assets folder into a jquery script within a grails application? Below is the jquery code snippet I have written to handle this: let dropdown = $('#banks'); dropdown.empty(); dropdown.append(' ...