Home > Back-end >  Get JsonResult within ActionResult
Get JsonResult within ActionResult

Time:10-11

My data is being generated at a JsonResult which output is below.

public JsonResult SampleAAA(Guid xxxxx){
    
    //Code ...

    return Json(new
    {
        success = true,
        listA,
        listB,
    }, JsonRequestBehavior.AllowGet);
}

From an ActionResult I need to call that JsonResult and get those lists.

public ActionResult SampleBBB(Guid xxxxx){

    var result = SampleAAA(xxxx);
    //How can I access 'listA' and 'listB' ?

    //Other code ...

    Return View();
}

How can I access those lists? I do see result.Data content, but I can't reach those lists to continue my code at Visual Studio.

CodePudding user response:

you can try this code

 var result = SampleAAA(xxxx);

 var jsonObject = (JObject)result.Value;

 bool success =  (bool)jsonObject["success"];

and it's much better to use JsonResult

return new JsonResult(new
    {
        success = true,
        listA,
        listB,
    });

CodePudding user response:

Using .Net 5 you can do this:

using System.Text.Json;

var doc = JsonDocument.Parse(YOUR_JSON);
var property = doc.RootElement.GetProperty("ListA");

CodePudding user response:

Thanks for all replies. After more research I've managed to solve with the code below.

public ActionResult SampleBBB(Guid xxxxx){

    var result = SampleAAA(xxxx);

    //Steps to have access to those information:
    string stringJson = JsonSerializer.Serialize(result.Data);
    var resultString = JObject.Parse(stringJson);
    var outputA = resultString["listA"].Value<string>();

    //...
    }
  • Related