ASP.NET MVC - ActionResult调用另一个JsonResult来获取数据?

时间:2011-03-21 18:59:04

标签: c# asp.net-mvc asp.net-mvc-3

我可以从ActionResult调用JsonResult方法吗?我想要做的是在我的MVC.Site项目中有一个专门用于处理API的区域(只返回json以便我可以重用非mvc项目)。然后从另一个ActionResult(我处理数据和视图),我想调用JsonResult,然后返回Json数据和View信息。即:

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
    });
}

感谢。

1 个答案:

答案 0 :(得分:6)

,这是完全可以接受的。

所有Results都继承自ActionResult。有关ActionResult课程的详细信息,请查看this article

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);
}
相关问题