Getting attributes of an object using jQuery

2

How do I get the attributes of an object that is returned by an action in the javascript ?

This is my code ajax .

Pass the id to the action and it returns an object. I would like to access the values of this object.

function UpdateDataPortfolio(id) {
    var parametros = {
        cd: id,
    };
    $.ajax({
        type: "POST",
        url: "/ManagementTables/UpdateDataPotfolio",
        data: parametros,
        datatype: "html",
        success: function (data) {
            alert(data);
        },
        error: function () {
            alert('failure');
        }
    });
}

This is the action :

    [HttpPost]
    public Portfolio UpdateDataPotfolio(String cd)
    {
        if (cd != null)
        {
            Portfolio port = portfolio.ListbyId(cd);
            return port;
        }


        return new Portfolio();
    }
    
asked by anonymous 30.06.2015 / 16:48

2 answers

3

For debugging purposes (which seems to be your case) use console.log() :

success: function (data) {
    console.log(data);
},

To access the properties of an object, use Object.keys() :

success: function (data) {
    var keys = Object.keys(data);

    for (var i = 0; i < keys.length; i++) {
    }
},

For part of Asp.Net, you might have to use ActionResult to return your object:

[HttpPost]
public ActionResult UpdateDataPotfolio(string cd)
{
    // retorno
    return Json(port);
}

And in your so-called ajax, switch dataType: "html" to dataType: "json" , since you're expecting a json , as defined in docs . Then the method Json() is in charge of transforming its class Portifolio into json to be read correctly in return. I do not know if I understand your intent in this request, if not, please let me know.

    
30.06.2015 / 16:49
0

When accessing attributes, consider that the element is accessed as follows:

By class (s): '.nome_classe1, .nome_classe_2'
By Id (s): '#elem_1, #elem_2'
By item (s): 'body, html, div'

Pass the list inside the object in jQuery $('aqui')
And to change attributes: $('obj').attr('nome_atributo','novo_valor');
To get the value of an attribute: $('obj').attr('nome_atributo');

You can access values by object ID, using the .val() method Example:


function getObj(id)
{
   var valor = $('#'+id).val();
   console.log(valor);
}

If the element is a div, you can access it using the .text() method, if it is a text or .html() , if it is HTML content.

    
30.06.2015 / 18:10