我可以从 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/