How to read data in Json on the server?

7

I have an Asp.Net MVC project and I am trying to reuse an Action that returns Json inside the server, but I am not able to work with Json returns in C #.

I'm doing research, but I have not found anything that will help me so far.

Code snippet:

public ActionResult MinhaAction(int param) 
{ 

   var minhaListaDeObjetos = new List<int>(){ 1, 2, 3};

   return Json(new 
      { 
        success = true, 
        data = minhaListaDeObjetos 
      }, JsonRequestBehavior.AllowGet); 
}

In another Action I have:

var resultado = MinhaAction(param);

How to access data within resultado ?

I've been trying like this:

resultado.data.minhaListaDeObjeto.First();

The result should be 1 , but this line does not work.

    
asked by anonymous 02.12.2015 / 20:33

1 answer

7

This is the wrong way to do it. Actions should return values only for requests, not internal functions.

The correct way to do this is through Helpers , static classes that serve just the purpose of being reused. For example:

public ActionResult MinhaAction(int param) 
{ 
   // Vamos passar isto para um Helper
   // var minhaListaDeObjetos = new List<int>(){ 1, 2, 3};
   var minhaListaDeObjetos = MeuHelper.TrazerLista();

   return Json(new 
      { 
        success = true, 
        data = minhaListaDeObjetos 
      }, JsonRequestBehavior.AllowGet); 
}

Helper is:

public static class MeuHelper 
{
    public static IEnumerable<int> TrazerLista()
    {
        return new List<int> { 1, 2, 3 };
    }
}

You do not need to make JSON circular inside the C # code because JSON is not a C # data structure. It is a structure that is serialized for a return at some point.

Lists and dictionaries better fulfill this function.

    
02.12.2015 / 20:37