How to parse the object (and its elements) from an ajax query

advertisements

Here's my issue. I'm making an ajax request to obtain an object from a controller. The object (or something) is being brought back, but I don't know how to access the attributes of that object being brought back. The object is of type "Address" and thus has attributes like Address.Address1, Address.City, etc. Here is my code: After a button is clicked,

function showEditAddress(addressid) {

    $.get("/Website/Accommodation/AddressGet",
        { guid: addressid.toString() },

        function(data) {

             //Get values from variable 'data' such as described above
             //and append to form 'dialog'

            $("#dialog").dialog({
                // autoOpen: false,
                show: {
                    effect: "explode",
                    duration: 250
                },
                hide: {
                    effect: "explode",
                    duration: 250
                },
                buttons: {
                    "Save": {
                        text: "Save",
                        class: "",
                        click: function () {
                             //save form
                            $(this).dialog("close");

                        }
                    },
                    "Cancel": {
                        text: "Cancel",
                        class: "",
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                },
                modal: true
            });
        });
    }

Controller action:

        public Address AddressGet(string guid)
    {
        Guid g = new Guid(guid);
        return _iCoreRepository.Addresses.Where(p => p.AddressID == g).SingleOrDefault();
    }

Any help will be greatly appreciated!!! Thank you!!!


Jose is quite simple. You already answer the question. To get the value of the properties of Address you only need put a dot in front of data and type de property name. like this:

//(....)
function(data) {

    //Get values from variable 'data' such as described above
    //and append to form 'dialog'

    //show address id.
    alert(data.AddressID);

Remember that javascript is case sensitive, so you need use upper case to A and ID in AddressID like you did in C#.

And in controller you need replace the last line to something like this:

var address = _iCoreRepository.Addresses.Where(p => p.AddressID == g).SingleOrDefault();
return Json(address, JsonRequestBehavior.AllowGet);

the method must be return JsonResult. The method Json serialize the object, in this case address, in a json format before response the data to the client.

If you need the Json method accepts IEnumerables to, like List<> or Array. In javascript your data object will be a lenght property and will acess each element by using indexer like:

data[0].AddressID.