开发者

Changing the view (.aspx) from the code-behind (.aspx.cs) class

I have a 'classic' ASP.NET app (.NET 3.5) with a pretty standard runat="server" style form with server-side controls and an 'Execute' asp:button. In the code-behind, the executeButton_click handler processes some of the other controls, runs a report, and drops the result into an asp:label. So the effect of pressing the Execute button is that the entire page reloads with the report inserted into the label.

I need to change this so that when the Execute button is pressed, the report pops up in a new window with a different layout (ie without the controls and form). If I was doing this in an MVC framework I would just change the view template in the 'execute' action, so the an开发者_开发知识库alogue for ASP.NET would be change the code in front, ie the .aspx file that gets used, from the code-behind class.

Is this possible? I know the link between the .aspx and the .aspx.cs isn't extremely tight as it is possible to reuse a code-behind class in multiple .aspx files. So can I set the .aspx file to render from the code-behind?


Normally you would direct the user to the new page by using

Response.Redirect("UrlToNewPage.aspx");

However if you need to access properties of the controls that are on the original form there is another approach you can take. Change the "PostBackURL" property of the asp:button to the second page. Then on the second page set the (@Page PreviousPageType) directive at the top of the aspx file, this tells this page that it is intended as the target of a post from page1.aspx. Then, in the code behind of the second page you can access the controls on the first page using the Page.PreviousPage property

For code sharing purposes you can create a base class and have both aspx.cs classes inherit from this base class if you want shared code.


I think this isn't possible because of the way ASP.NET works. The view file in ASP.NET is dynamically compiled into a subclass of the code-behind class by the ASP.NET engine. When the URL is requested, the subclass is what is instantiated and executed. Changing the view from the code-behind class is trying to change the concrete type. We can have multiple .aspx files inheriting from a single code-behind class, but not vice versa.

Non-ASP.NET frameworks would be able to do this because the view is just a template file that is processed on the fly by the framework after the controller action is complete, so the view can be changed without bothering with inheritance issues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜