我怎样才能创建asp.net页面的扩展方法 [英] How I can create an extension method for asp.net page
问题描述
我怎样才能创建Asp.net MVC像Html.DisplayTextFor扩展方法?我的意思是我需要像Page.DisplayTextFor我怎么能实现它asp.net我的网页类的扩展。我创建了这一点:
How I can create an extension method like "Html.DisplayTextFor" in Asp.net mvc ? I mean I need an extension for my page class in asp.net like "Page.DisplayTextFor" how I can implement it. I have created this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace System.Web.UI
{
public static class PageExtension
{
public static void DisplayTextFor(this string text)
{
/*some operation*/
}
}
}
,但它不工作
推荐答案
我假设你的意思是你想扩展Page类添加自己的功能,使用时出现 this.Page ...
?
I assume you mean you want to extend the Page class adding your own functions to appear when using this.Page...
?
如果是这样,首先必须在 PageExtension
类的<strong>您自己的命名空间的一部分。那么语法是:
If so, first have the PageExtension
class as part of your own namespace. Then the syntax is:
public static void DisplayTextFor(this Page page, string text)
{
page.Response.Write(text);
}
扩展方法第一个参数定义扩展什么课,其余参数定义您调用它时送什么。
The extension method first parameter defines what class to extend, the rest of the parameters define what you send when calling it.
要拨打以上从你的页面中,刚好有:
To call the above from within your page, just have:
this.Page.DisplayTextFor("hello world");
这篇关于我怎样才能创建asp.net页面的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!