How to read data in Json on the server?

Asked

Viewed 280 times

7

I have an Asp.Net MVC project and I’m trying to repurpose an Action that returns Json within the server, but I’m unable to work with Json returns in C#.

I’m doing research, but I haven’t found anything to help me so far.

Excerpt from the code:

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 so:

resultado.data.minhaListaDeObjeto.First();

The result should be 1, but that line doesn’t work.

1 answer

7


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

The correct way to do this is through Helpers, static classes that serve precisely 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); 
}

The Helper stays:

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

You do not need to circulate JSON 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 perform this function better.

Browser other questions tagged

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