[英]ASP.NET MVC - ActionResult calling another JsonResult to get data?
我可以從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
});
}
謝謝。
是的 ,這是完全可以接受的。
所有Results
都繼承自ActionResult
。 有關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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.