【问题标题】:ASP.NET MVC - ActionResult calling another JsonResult to get data?ASP.NET MVC - ActionResult 调用另一个 JsonResult 来获取数据?
【发布时间】:2011-03-21 18:59:04
【问题描述】:

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

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

谢谢。

【问题讨论】:

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


    【解决方案1】:

    是的,这是完全可以接受的。

    所有Results 都继承自ActionResult。查看this article 了解ActionResult 类的详细信息。

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

    【讨论】:

    • 我想你错过了理解我的问题,我知道我可以返回 Json,即使返回类型是 ActionResult。我的问题是我可以在 ActionResult 中调用 JsonResult 方法吗?因为现在,如果我在 ActionResult 方法中调用 JsonResult 方法,我得到的回报是:Controller: "Music", Action: "GetSongs", RouteValueDictionary: [ .. ...
    • 好吧,如果您只对数据感兴趣,那么您可以使用JsonResult.Data 属性。我会更新答案。
    • Josiah,如果两种方法(JsonResultActionResult)都来自同一个控制器,那么我可以获取数据。但是,如果 JsonResult 来自不同的控制器(并且此控制器来自不同的区域 - 我使用区域来分隔 API 内容),则 Data 始终为空(因为看起来 JsonResult 方法似乎永远不会被调用。)如何从不同的控制器/区域调用该方法?谢谢。
    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 2016-08-23
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多