1. 程式人生 > >.net mvc控制器傳遞方法到視圖

.net mvc控制器傳遞方法到視圖

測試 mode ring 一個 傳遞 代碼 mvc控制器 cap del

很多人都是在視圖裏面定義方法,然後再使用。我個人也是這麽幹的。但是為了驗證是否可以將方法從控制器傳遞到視圖,所以做了個測試。結果真的可以。原理是利用了委托(delegate),因為委托本身就是一種類型。既然是類型,那麽就有實例。有了實例就可以作為View()方法的參數傳遞到視圖。

下面貼代碼:

ActionResult:

        public delegate string MyDelegate(string content);

        public ActionResult DelegateTest()
        {
            MyDelegate myDelegate 
= (string content) => { return content; }; return View(myDelegate); }

視圖:

<h2>DelegateTest</h2>

@model MvcApplication1.Controllers.TestController.MyDelegate

@Model("delegate test")

既然委托都可以了,那麽C#內置的Func<>委托肯定也是可以的

ActionResult:

        public
ActionResult FunTest() { Func<string, string> myDelegate = (string content) => { return content; }; return View(myDelegate); }

視圖:

<h2>FunTest</h2>

@model System.Func<string, string>

@Model("fun test")

使用Func<>或者Action<>委托的好處就是不需要再自定義委托類型了。

有人會說,你傻啊,定義一個類,在類裏面寫方法不就行了。可咱這只是純為了驗證是否能實現。

.net mvc控制器傳遞方法到視圖