rakshith
rakshith

Reputation: 784

How to retrieve JsonResult data

I have the following Action in my layouts Controller

public JsonResult getlayouts(int lid)
{
    List<layouts> L = new List<layouts>();
    L = db.LAYOUTS.Where(d => d.seating_plane_id == lid).ToList()

    return new JsonResult { Data = L, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

I am calling this Action from another controller like so:

layoutsController L = new layoutsController();
JsonResult result = L.getlayouts(lid);

My question is: how can I get the data from result object?

Upvotes: 6

Views: 19058

Answers (2)

Mat&#237;as Gallegos
Mat&#237;as Gallegos

Reputation: 121

I have my class:

public class ResponseJson
{
    public string message { get; set; }
    public bool success { get; set; }
}

in my method SendEmail

private async Task<JsonResult> SendEmailAsync(ApplicationUser user, string returnUrl, string empleadoNombre, string pwdInic)

i will return my JsonResult

ResponseJson response = new ResponseJson();

response.success = true;
response.message = "Operación exitosa";

return new JsonResult( response);

to read the result returned from my SendEmail method

JsonResult emailSend = await SendEmailAsync(user, returnUrl, empleadoNombre, pwdInic);
ResponseJson response = new ResponseJson();
                
try
{ 
      string json = JsonConvert.SerializeObject(emailSend.Value);
      response = JsonConvert.DeserializeObject<ResponseJson>(json);

}
catch(Exception e)
{

}

emailSend

response

Upvotes: 1

David
David

Reputation: 218798

Well, have a look how you're building the object:

new JsonResult { Data = L, JsonRequestBehavior = JsonRequestBehavior.AllowGet }

You're setting the L variable to a property called Data. So just read that property:

List<layouts> L = (List<layouts>)result.Data;

There's nothing special about the fact that it's an MVC controller action.

You're simply calling a method which returns an object that was constructed in the method, and reading properties from that object. Just like any other C# code.

Upvotes: 6

Related Questions