Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - ActionResult calling another JsonResult to get data?

Can I call a JsonResult method from my ActionResult? What I'm trying to do is to have an Area in my MVC.Site project to deal specifically with API (just return json so that I can reuse with non-mvc projects). And then from a different ActionResult (where I deal with data AND views), I would like to call the JsonResult and then return that Json data along with View information. i.e:

public JsonResult GetSongs()
{
    var songs = _music.GetSongs(0, 3);
    return Json(new { songs = songs }, JsonRequestBehavior.AllowGet);
}

public ActionResult Songs()
{
    // Get the data by calling the JsonResult method
    var data = GetSongs();
    return Json(new
    {
        // Render the partial view + data as json
        PartialViewHtml = RenderPartialViewToString("MyView", data),
        success = true
    });
}

Thanks.

like image 272
Saxman Avatar asked Mar 21 '11 18:03

Saxman


1 Answers

Yes, that is perfectly acceptable.

All Results inherit from ActionResult. Have a look at this article for detailed information on ActionResult class.

public JsonResult GetSongs()
{
    var songs = _music.GetSongs(0, 3);
    return Json(new { songs = songs }, JsonRequestBehavior.AllowGet);
}
public ActionResult GetSongs()
{
    var result = GetSongs();
    return Json(new
    {
        // The JsonResult contains additional route data and view data. 
        // Your view is most likely interested in the Data prop (new { songs = songs })
        // depending on how RenderPartialViewToString is written you could also pass ViewData
        PartialViewHtml = RenderPartialViewToString("MyView", result.Data),
        success = true
    }, JsonRequestBehavior.AllowGet);
}
like image 111
Josiah Ruddell Avatar answered Nov 01 '22 10:11

Josiah Ruddell