ASP.Net MVC 中是否有與 Ruby on Rails 的 respond_to format.xml 等等價的東西?
在 Ruby on Rails 中,您可以編寫一個簡單的控制器操作,例如:
def index @movies = Movies.find(:all) respond_to do |format| format.html #index.html.erb format.xml { render :xml => @movies } format.json { render :json => @movies } end end對於那些不熟悉 RoR 的人,
def index在這種情況下相當於public ActionResult Index()在 ASP.Net MVC 控制器中,並允許以下呼叫:
http://example.com/Movies/Index從視圖返回為 html 頁面index.html.erb(想想 index.aspx)
http://example.com/Movies/Index.xml以 xml 格式返回相同的數據(@movies是包含所有視圖使用的數據的對象)
http://example.com/Movies/Index.json返回 JSON 字元串,在進行需要相同數據/邏輯的 javascript 呼叫時很有用ASP.Net MVC 中的等效流程(如果可能)可能看起來像這樣(如果它可以不那麼冗長,甚至更好):
public ActionResult Index() { Movies movies = dataContext.GetMovies(); // any other logic goes here switch (format) { case "xml": return View("XMLVIEW"); break; case "json": return View("JSONVIEW"); break; default: return View(); } }這真的很方便,不必讓一堆不同的動作弄亂你的控制器,有沒有辦法在 ASP.Net MVC 中做類似的事情?
所以我一直在玩這個並將以下路由添加到 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 = "" });現在,每當我需要控制器動作來“辨識格式”時,我只需
string format向它添加一個參數(例如):// Within Home Controller public ActionResult MovieList(string format) { List<Movie> movies = CreateMovieList(); if ( format == "json" ) return Json(movies); return View(movies); }現在,當我呼叫
/Home/MovieList它時,它會像往常一樣返回標準的 html 視圖,如果我呼叫/Home/MovieList.json它,它會返回傳遞給視圖的相同數據的 JSON 序列化字元串。這適用於您碰巧使用的任何視圖模型,我使用一個非常簡單的列表只是為了修補。為了使事情變得更好,您甚至可以在視圖中執行以下操作:
連結到
/Home/MovieList
<%= Html.ActionLink("Test", "MovieList") %>連結到
/Home/MovieList.json
<%= Html.ActionLink("JSON", "MovieList", new { format = "json" }) %>
在我的部落格中,我詳細介紹了一種處理此問題的方法,該方法的功能與它在 Ruby on Rails 中的功能非常相似。您可以在文章底部找到連結,但這裡是最終結果的範例:
public ActionResult Index() { return RespondTo(format => { format.Html = () => View(); format.Json = () => Json(new { message = "hello world" }); }); }這是文章的連結:http: //icanhascode.com/2009/05/simple-ror-respond_to-functionality-in-aspnet-mvc/
它可以通過 HTTP 標頭以及路由中的變數來處理檢測正確的類型。