更新时间:2023-01-06 22:26:45
所以,我一直在玩这个,并增加了以下路线的RegisterRoutes():
So I've been playing with this and added the following routes to RegisterRoutes():
routes.MapRoute("FormatAction", "{controller}/{action}.{format}",
new { controller = "Home", action = "Index" });
routes.MapRoute("FormatID", "{controller}/{action}/{id}.{format}",
new { controller = "Home", action = "Index", id = "" });
现在,每当我需要一个控制器动作被格式化意识到我只需要添加一个字符串格式
参数把它(如):
Now whenever I need a Controller Action to be "format aware" I simply add a string format
argument to it (such as):
// Within Home Controller
public ActionResult MovieList(string format)
{
List<Movie> movies = CreateMovieList();
if ( format == "json" )
return Json(movies);
return View(movies);
}
现在,当我打电话 /主页/ MovieList
返回标准的HTML视图一如既往,如果我做出 /主页/ MovieList打电话。 JSON
返回传递到视图中的同一数据的JSON序列串。这适用于任何浏览模式工作,你碰巧使用的,我用一个很简单的列表只是修修补补的缘故。
Now when I call /Home/MovieList
it returns the standard html view as always and if I make a call to /Home/MovieList.json
it returns a JSON serialized string of the same data passed into the view. This will work for any view model you happen to be using, I'm using a very simple list just for the sake of tinkering.
为了让事情更好,你甚至可以做视图中的以下内容:
To make things even better you can even do the following within the views:
链接 /主页/ MovieList
结果&LT;%= Html.ActionLink(测试,MovieList)%&GT;
链接 /Home/MovieList.json
结果&LT;%= Html.ActionLink(JSON,MovieList,新{格式=JSON})%&GT;