kamiar3001
kamiar3001

Reputation: 2676

How I can create an extension method for asp.net page

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*/
            }
        }
    }

but it doesn't work.

Upvotes: 1

Views: 3496

Answers (2)

Shadow Wizard
Shadow Wizard

Reputation: 66389

I assume you mean you want to extend the Page class adding your own functions to appear when using this.Page...?

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");

Upvotes: 4

SLaks
SLaks

Reputation: 887453

You need to pick an existing property in the System.Web.UI.Page class to extend, or create your own property (in a base class) and your own class.

Upvotes: 0

Related Questions