简体   繁体   中英

display json data from controller inside view

Inside my controller there is JsonResult action which returns me a list of House object. I want onclick using ajax to retrieve these data and to display json data inside my view. Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.

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

        success: function (result) {
           // tried with these but it doesnt work
           // result = jQuery.parseJSON(result);
           // alert(result.Title);
        },
        error: function () { alert("error"); }
    });
}

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


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

Inside firebug JSON tab when success:function(result) is empty I have following data:

Id  149

PropertyType    "Apartment"

StreetNumber    "202B"

CityName        "Sidney"

Title           "My test data"

First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -

dataType: 'json'

Then, you don't need to use parseJSON. Simply use result.Title etc.

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

EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.

The ajax call result is already an object. You can do whatever you want with it it inside the success function.

For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.

Access the data object like any object (data.someProperty).

success: function (json) {
  var data = null;

  $.each(json.items,function(item,i){
    data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';    
    $("#showContent").append(data);
 });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM