Show the JSON response from the controller on the view page

In my controller, I have a JsonResult action that returns a list of House objects. My goal is to retrieve this data onclick using ajax and display the JSON data within my view. While I can see the proper response and JSON result in Firebug, I'm not sure how to display it in my view.

function FetchData(id) {
    $.ajax({
        url: ('/Home/FetchData'),
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ id: id }),

        success: function (result) {
           // attempted parsing but didn't work
           // result = jQuery.parseJSON(result);
           // alert(result.Title);
        },
        error: function () { alert("error"); }
    });
}

public JsonResult FetchData()
{
   ...
   var temp = getMyData...
   return Json(temp, JsonRequestBehavior.AllowGet);   
}


  // View page
     <div id="showContent">
       // JSON data should appear here
     </div>

In Firebug's JSON tab, when success:function(result) is empty, the following data is displayed:

Id  149

PropertyType    "Apartment"

StreetNumber    "202B"

CityName        "Sidney"

Title           "My test data"

Answer №1

onSuccess: function (jsonData) {
  var content = null;

  $.each(jsonData.entries,function(entry,index){
    content = '<span>'+entry.code+ ' | ' + entry.name +'</span>';    
    $("#displayArea").append(content);
 });

}

Answer №2

To start with, when making your ajax call, you can set the dataType attribute to 'json' so that you won't have to decode the json response again -

dataType: 'json'

By doing this, there is no need for parseJSON. You can simply access result.Title directly.

 success: function (result) {
           alert(result.Title);
           var showContent = $('#showContent');
           showContent.html(result.Id+','+result.Title);
        },

Answer №3

UPDATE: Just like Mukesh mentioned, the ajax function has the capability to return json without the need for additional decoding steps.

The result of the ajax call is already in object form. You have full control over how you want to manipulate it within the success function.

One possibility is creating a dynamic table displaying the information directly inside the function, or passing the data to another function by invoking it from within the success function. Once you exit the success function, the data becomes inaccessible.

Access the data object similar to any other object (data.someProperty).

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

Unknown error occurred in Eventstore: Unable to identify the BadRequest issue

I'm encountering an error while using Eventstore, specifically: Could not recognize BadRequest; The error message is originating from: game process tick failed UnknownError: Could not recognize BadRequest at unpackToCommandError (\node_modul ...

Converting a Jquery object into a Javascript object

Can someone help me decipher this piece of code? //... obj.dd.on('click', function(event){ $(this).toggleClass('active'); return false; }); //... $(function() { var dd = new DropDown( $('#dd') ); $(doc ...

Adding data to a JSON object using AngularJS

When attempting to insert an object into a JSON object, I am encountering an issue where it duplicates the JSON object. Here is a breakdown of the scenario: <input type="text" style="width: 40% !important;" placeholder="Nom" class="input-sm" ng-model= ...

Problems with ng-repeat in kenwheeler's AngularJS implementation

Hey there! I'm currently using the slick carousel by ken wheeler, but when I implement ng-repeat on the div, it only shows 'listed images'. I'm not sure what I'm doing wrong here. Any ideas? <section class="regular slider" sty ...

Switch up primary and secondary color schemes with the Material UI Theme swap

Exploring Material UI themes for React JS is a new venture for me. I am facing a scenario where I need to dynamically change the theme colors (Primary & Secondary) based on a selected type from a dropdown menu. Similar to the color customization options av ...

Ways to receive responses from PHP with jQuery AJAX

Hey there, I'm currently working on echoing specific messages from my PHP code back to my AJAX function. Usually, I only have one message to echo, but this time I have two. I'm not sure how to assign each echo to a different .html() element. $(" ...

Retrieve the genuine HTML code for a control directly on the client side

My goal is to retrieve the complete HTML text for a control from the client browser. This is important because certain information, especially the "Style," does not appear on the server side. How can I obtain the entire HTML text for a control? ...

Steps to generate a newline-separated JSON-lines file from a collection of Python dictionaries

To meet the requirements for online prediction on Google Cloud AI platform, I am working on creating a JSON-lines file containing my data. My data is currently stored as a list of dictionaries, structured like this: data = [{'values': [0,1,0], ...

Sending information from MVC controller back to the originating view

Being relatively new to asp.net MVC, I have encountered a challenge that I hope someone can assist me with. My issue revolves around a text box where users input search terms. Upon clicking the search button, an Ajax call is made to pass the textbox value ...

Discover the power of sorting outcomes in a Node.js-MongoDB query by utilizing a dynamic function call

Currently, I am working on a web application in Node.js that is connected to MongoDB using the Mongo native connector. In one of my JavaScript files, I have implemented a generic method to perform "find" or "findOne" operations to fetch data from a collec ...

Add a new row to the table when a dropdown option is selected, and remove the row when deleted. Ensure that the row is only added

Here is my specific requirement: I need a table with a default row containing a dropdown menu in the first column. When an option is selected from the dropdown, a new table row should be added with the same content as the main row and a delete button for ...

Exploring the functionality of Array.IndexOf with a jagged array

If I have a jagged array structured like this: [0][0]{128} [0][1]{512} [1][0]{64} How can I retrieve the indexes of a specific number within the array? For example, if I wanted to find the index of 64, I would like to output something like 0,1 to indicat ...

Upon the initial rendering, Next.js obtains access to the query { amp: undefined }

When using Next.js 9.3, I encountered an issue where I needed to access the query on initial render and pass the result of the query to next/head in order to change the title and description of the page. The component is receiving the query from the useRo ...

Can someone explain what logForm.$invalid.$setValidity is all about?

The code snippet can be found here I am a beginner in this field and currently studying a piece of code. I am having trouble understanding the logForm.$invalid.$setValidity line. I have searched online but couldn't find any information about it. The ...

What is the best method to retrieve the minimum and maximum values of a range slider in PHP and

I've successfully implemented a custom range slider using the code snippet below: HTML: <input type="text" class="salary" id="salary" name="salary" style="border:0; color:#f6931f; font-weight:bold;&qu ...

I encountered an error while trying to launch my server using Docker

My node JS server running in docker is throwing an error after a successful build. I have tried deleting the docker image, but it did not resolve the issue. ...

Guide to discovering an almost ascending sequence in an Array

I recently encountered a challenging algorithm problem that I need help with: "I have a sequence of integers stored in an array. My task is to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element f ...

Deliver an assured result to a variable within the angular.extend() function

Can someone provide guidance on how to set myVar to a value returned from an asynchronous service method in the following example? angular.extend(this, { myVar: (function() { getVal(); })() }); function getVal() { var d = $q.defer(); ...

The contrast between FormData and jQuery's serialize() method: Exploring the distinctions

Recently I came across a situation where I needed to submit a form using AJAX. While researching the most efficient method, I discovered two popular approaches - some developers were utilizing jQuery#serialize() while others were opting for FormData. Here ...

Encountering issues with Play Framework's routing system resulting in a 400 bad

I'm currently facing an issue with sending a POST request to the play framework - it seems like this problem could be more related to HTTP than Play itself. $.ajax({ type:'POST', url:'http://localhost:9000/start', data ...