[英]ASP.NET MVC - ActionResult calling another JsonResult to get data?
Can I call a JsonResult method from my ActionResult? 我可以从ActionResult调用JsonResult方法吗? What I'm trying to do is to have an Area in my MVC.Site project to deal specifically with API (just return json so that I can reuse with non-mvc projects). 我想要做的是在我的MVC.Site项目中有一个专门用于处理API的区域(只返回json以便我可以重用非mvc项目)。 And then from a different ActionResult (where I deal with data AND views), I would like to call the JsonResult and then return that Json data along with View information. 然后从另一个ActionResult(我处理数据和视图),我想调用JsonResult,然后返回Json数据和View信息。 ie: 即:
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
});
}
Thanks. 谢谢。
Yes , that is perfectly acceptable. 是的 ,这是完全可以接受的。
All Results
inherit from ActionResult
. 所有Results
都继承自ActionResult
。 Have a look at this article for detailed information on ActionResult
class. 有关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.