开发者

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 sp开发者_StackOverflow中文版ecifically 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜