[ASP.NET MVC]讓Html.RenderAction支援Lamda運算式

來源:互聯網
上載者:User

今天在ASP.NET MVC代碼時用到了Html.RenderAction,代碼如下:

@{Html.RenderAction("RecentNews")}

通過字串指定Action的名稱,有兩點不爽:

1. 輸入時不能智能感知;

2. 輸錯了不能即時提示。

有這兩點不爽,寫代碼的樂趣就大減。有享受感覺的代碼應該是這樣的: 

@{Html.RenderAction<AggSiteController>(c => c.RecentNews());}

是的,Lamda,給你寫代碼帶來暢快感覺的Lamda!

微軟不讓我們享受,我們就自己動手,豐衣足食。自己寫一個支援Lamda運算式的Html.RenderAction,代碼如下:

using System.Web.Mvc;using System.Web.Mvc.Html;using System.Linq.Expressions;namespace System.Web.Mvc.Html{    public static class HtmlHelperExtensions    {        public static void RenderAction<TController>(this HtmlHelper htmlHelper,             Expression<Action<TController>> operation)             where TController : Controller        {            var actionName = ((MethodCallExpression)operation.Body).Method.Name;            htmlHelper.RenderAction(actionName);        }    }}

註:其中"((MethodCallExpression)operation.Body).Method.Name"代碼來自Get Method Name From Action。

順帶分享一篇文章When to use Html.RenderPartial and Html.RenderAction in ASP.NET MVC Razor Views,通過這篇文章你可以清楚的知道Html.RenderPartial與Html.RenderAction之間的區別。

比如:部落格園首頁的最新隨筆列表就適合用Html.RenderPartial,而右側的“新聞列表”就適合用Html.RenderAction。

簡單的理解就是:Html.RenderPartial用的到PartialView只用一次(雖然實際可以多次使用,但比較麻煩,每次都要傳Model),Html.RenderAction用的到PartialView被多個視圖使用(有自己的Action提供Model)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.