Function that returns other functions

Asked

Viewed 76 times

3

I have three methods being called separately on controller with JSON. Each one of them returns to me Id Name.

I need to call these three methods in the same function in the controller. How can I join the three methods in the same function?

[HttpPost]
public ActionResult GetMessageClassByResourceByDevice(int resourceId, string deviceName)
{                
    return  Json(EventFlow.GetMessageClassByResourceByDevice(resourceId, deviceName)
        .Select(f => new { EventMessageClassId = f.Id, FullName = f.Name }));

}

[HttpPost]
public ActionResult GetMessageGroupByResourceByDevice(int resourceId, string deviceName)
{
    return Json(EventFlow.GetMessageGroupByResourceByDevice(resourceId, deviceName)
        .Select(f => new { EventMessageGroupId = f.Id, FullName = f.Name }));

}

[HttpPost]
public ActionResult GetMessageByResourceByDevice(int resourceId, string deviceName)
{
    return Json(EventFlow.GetMessageByResourceByDevice(resourceId, deviceName)
        .Select(f => new { EventMessageId = f.Id, FullName = f.Name }));
}
  • 1

    I’m not sure what you want, but it doesn’t look like you can improve much more than that. I think, but I could be wrong that you’re trying to do DRY where it doesn’t fit. Check this out: http://answall.com/q/120931/101 But if you explain it better, I can try to see if something can be done.

  • 1

    Each Action returns a JsonResult different. What’s the idea? Join all JSON into one?

1 answer

0

If you want to return the list of the contents of the three method returns, you can do the following:

[HttpPost]
public ActionResult GetMessageClass(int resourceId, string deviceName)
{
  var list = new List<dynamic>();

  list.Add((dynamic)GetMessageClassByResourceByDevice(resourceId, deviceName).Data);
  list.Add((dynamic)GetMessageGroupByResourceByDevice(resourceId, deviceName).Data);
  list.Add((dynamic)GetMessageByResourceByDevice(resourceId, deviceName).Data);

  return Json(list);
}

If you want to return the first of the non-zero returns, you can do the following:

[HttpPost]
public ActionResult GetMessageClass(int resourceId, string deviceName)
{
  var ret = (dynamic)GetMessageClassByResourceByDevice(resourceId, deviceName).Data;
  if (ret != null) {
    ret = (dynamic)GetMessageGroupByResourceByDevice(resourceId, deviceName).Data;
  }
  else if (ret != null) {
    ret = (dynamic)GetMessageByResourceByDevice(resourceId, deviceName).Data;
  }

  return Json(ret);
}

Browser other questions tagged

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