[英]How to tell an MVC 4 View to return a JSON result with a sub route
What I want is a solution for the next problem: 1. I have an MVC 4 view + controller that renders Index and another for Details 2. to access that information I go to http://localhost:1234/Movies
and to http://localhost:1234/Movies/1
(for details) 3. I want to create a new route http://localhost:1234/json/Movies
and http://localhost:1234/json/Movies/1
4. in the Method of Index I want the code to be like: 我想要的是下一个问题的解决方案:1.我有一个MVC 4视图+控制器,它呈现索引,而另一个用于呈现Details。2.访问该信息,我去
http://localhost:1234/Movies
和http://localhost:1234/Movies/1
(有关详细信息)3.我想创建一个新路由http://localhost:1234/json/Movies
和http://localhost:1234/json/Movies/1
4.在我希望代码的索引方法如下:
public ActionResult Index(string format)
{
return View(db.Movies.ToList());
}
or 要么
public ActionResult Index(string format)
{
return ChooseView(db.Movies.ToList());
}
and I want the view to render the corrent (html\\json) according to the route. 我希望视图根据路线呈现相应的(html \\ json)。
Is that possible? 那可能吗?
Thanks. 谢谢。
public class MoviesController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(string format)
{
return ToResult(db.Movies.ToList(), format);
}
}
This will make /Movies
get the HTML page rendered by the view Index.cshtml
and /Movies?format=json
get the list of movies as JSON data. 这将使
/Movies
获取由视图Index.cshtml
呈现的HTML页面,而/Movies?format=json
获取作为JSON数据的电影列表。
public static ActionResult ToResult(object data, string format)
{
if (format == "json")
{
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
return View(data);
}
}
use return Json(data) 使用return Json(data)
for detail visit 详细访问
http://programming-pages.com/2012/10/24/json-with-asp-net-mvc-4/ http://programming-pages.com/2012/10/24/json-with-asp-net-mvc-4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.