Picking attributes from an object using jQuery

Asked

Viewed 4,299 times

2

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

This is my code ajax.

Step the id for the action and it returns an object. I would like to access the values of that 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');
        }
    });
}

That’s the action:

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


        return new Portfolio();
    }

2 answers

3

For debug purposes (which seems to be your case) use the 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++) {
    }
},

Regarding the Asp.Net part, maybe you should use the Actionresult to return your object:

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

And in your ajax call, change dataType: "html" for dataType: "json", 'cause you’re expecting a json, as defined in Docs. So the method Json() takes charge of transforming your class Portifolio in json to be read correctly in return. I’m not sure I understand your intention in this request, if not, please let me know.

  • 1

    There is still the JsonResult, which I consider better than the ActionResult for this case.

  • I got it using Json. Thank you

  • @Gypsy omorrisonmendez good option also.

  • @Paul if this is the answer to the question, please mark it as such.

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'
Per element(s): 'body, html, div'

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

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


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

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

  • Actually I think you got it wrong. The OP wanted to access the properties(ok, it called attributes) of a object javascript and not a element GIFT.

  • The question seemed a little confusing indeed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.