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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With