c# - 如何为 asp.net 页面创建扩展方法

标签 c# asp.net

如何在 Asp.net mvc 中创建类似“Html.DisplayTextFor”的扩展方法?我的意思是我需要在 asp.net 中为我的页面类扩展,如“Page.DisplayTextFor”,我如何实现它。我创建了这个:

    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... 时出现?

如果是这样,首先将 PageExtension 类作为您自己的 命名空间的一部分。那么语法是:

public static void DisplayTextFor(this Page page, string text)
{
    page.Response.Write(text);
}

扩展方法第一个参数定义要扩展的类,其余参数定义调用它时发送的内容。

要从您的页面中调用上述方法,只需:

this.Page.DisplayTextFor("hello world");

关于c# - 如何为 asp.net 页面创建扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8286323/

相关文章:

c# - 消息解析器 C#

c# - 找不到类型或命名空间名称 'TwilioRestClient'

c# - 基于变量动态访问 ASP.NET 控件...这可能吗?

c# - "Errors During Preprocessing"在 ASP.NET 性能计数器中非零

c# - 在 Linux Ubuntu 中开发 C#/ASP.NET 的软件

c# - 我如何诊断为什么 asp.net MVC 站点在一台服务器上运行但在另一台服务器上运行不正常?

c# - 如何用方法语法编写查询

c# - 对象的成员是否应该在类中自动设置?

c# - 使用 LINQ 分隔列表元素并将结果插入回列表

asp.net - 将asp.net core应用程序部署到azure后出错