ScampDoodle
ScampDoodle

Reputation: 296

Setting Page Async mode to true from Code-Behind

Is it possible within my code-behind file to set the asynchronous mode of the page directive.

I have no way of directly modifying the <%@Page %> attribute and and struggling to find a way to implement this in my code-behind.

I have tried in my Page_Load method to add Page.AsyncMode = true, but it returns the following error:

is inaccessible due to its protection level

Is there any way to do this? Without being able to directly modify the master page?

Upvotes: 4

Views: 6382

Answers (3)

Michael Liu
Michael Liu

Reputation: 55469

No, you cannot change the asynchronous mode of a page in the code-behind. An asynchronous page implements the IHttpAsyncHandler interface, and there is no way to change the interfaces implemented by your page after the .aspx file has been compiled by ASP.NET and your code is running.

Setting the Page.AsyncMode property will not change the asynchronous mode. Its purpose is to let controls on the page know whether the page is running in asynchronous mode or not, so tampering with the property may cause controls to malfunction.

Upvotes: 4

Eoin Campbell
Eoin Campbell

Reputation: 44298

Because you're MasterPage does not Inherit from your Page, you cannot access the AsyncMode Property.

If you absolutely must edit the value from your MasterPage maybe consider adding a method to your page called "UpdateAsyncMode" and doing the following from your masterpage Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        MyPageClass p = this.Page as MyPageClass ;

        p.UpdateAsyncMode(true);
    }

Alternatively if this is something that needs to be more robust you could create a base class for Pages like the following and have all the web pages in your site extend that base class

public abstract class MyBasePage : System.Web.UI.Page
{
    public void UpdateAsyncMode (bool b)
    {
        this.AsyncMode = b;
    }
}

Upvotes: 0

Oleks
Oleks

Reputation: 32343

My guess - you're trying to access this property from your master page. But according to documentation, this property is protected bool AsyncMode { get; set; }. Which means it is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.

This property is declared in System.Web.UI.Page and is accessible in it and any class derived from it. MasterPage doesn't derive from Page. That's why you cannot access it.

You can easily access it from your page:

public partial class YourPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.AsyncMode = true;
    }
}

Upvotes: 0

Related Questions