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

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

我可以从 ActionResult 调用 JsonResult 方法吗?我想要做的是在我的 MVC.Site 项目中有一个区域专门处理 API(只需返回 json 以便我可以重用非 mvc 项目)。然后从不同的 ActionResult(我处理数据和 View 的地方)调用 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
    });
}

谢谢。

最佳答案

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

所有 Result 都继承自 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);
}

关于c# - ASP.NET MVC - ActionResult 调用另一个 JsonResult 来获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5382294/

相关文章:

c# - 如何使用 Visual Studio Entity Framework 代码优先迁移部署发布到 mysql 数据库

c# - 如何首先循环遍历 Entity Framework 4.1 代码中的子对象列表

c# - 在字符串上使用 Razor 引擎 - 而不是 View

c# - 收据打印机上的 WPF PrintVisual 正在剪切图像

c# - 执行时 ASP.Net MVC "Could Not Load Type"

c# - 等同于 C# 中的 php fmod

asp.net-mvc - User.Identity.IsAuthenticated 注销 asp.net mvc 后为真

C# 任务异步等待智能卡 - UI 线程阻塞

c# - MVC AccountController 与 IsAuthenticated false OWIN

asp.net-mvc-3 - 即使密码相同,比较验证器也总是会触发