ASP.NET MVC Tip #22 – 無需建立 Controller Action 直接返回一個View

來源:互聯網
上載者:User

ASP.NET MVC Tip #22 – 無需建立 Controller Action 直接返回一個View
ASP.NET MVC Tip #22 – Return a View without Creating a Controller Action

美語原文:http://weblogs.asp.net/stephenwalther/archive/2008/07/21/asp-net-mvc-tip-22-return-a-view-without-creating-a-controller-action.aspx
國語翻譯:http://www.cnblogs.com/mike108mvp

譯者註:在下水平有限,翻譯中若有錯誤或不妥之處,歡迎大家批評指正。謝謝。

譯者註:ASP.NET MVC QQ交流群 1215279 歡迎對 ASP.NET MVC 感興趣的朋友加入

在這篇文章中,我將示範如何不使用controller 方法,而直接返回View。我將展示如何使用HandleUnknownAction 方法來自動處理對一個controller 的每個請求。

我看到Phil Haack在一個demo 中使用了下面的技巧。我認為這是很好的技巧,我必須和大家分享一下。

除非你有很好的理由,否則不要編寫代碼。我發現我寫了很多controller actions,它們並沒有做任何事情,只是返回一個View。例如,請看下面Listing 1中的CustomerController :

Listing 1 – CustomerController.cs

這個controller 包含三個action,返回三個不同的View。每個action包含一行代碼。事實上,每個action包含的是相同的一行代碼。這行代碼不是很必需的。如何修改它呢?

Controller 類包含一個HandleUnknownAction()方法,它在你試圖去調用一個不存在的action 時被執行。Listing 2中的controller 利用了HandleUnknownAction()方法,當沒有找到一個相應的controller 方法時,用它來呈現View,

Listing 2 – HomeController.cs

當你使用Listing 2中的controller 時,你可以調用任何action ,controller 將會嘗試返回一個對應的View。你不用為每個View顯式地編寫action 方法代碼。

注意controller 包含一個Details() action。當你需要傳遞ViewData時,那麼你需要顯式地編寫action 方法。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.