Dynamic Pages From a Database in C# - c#

Forgive me if this has already been asked somewhere, but I cannot figure out the best way to accomplish this task. I want to be able to create a rendering system that will allow me to render out content from thousands of different .aspx pages without having to create thousands of .aspx pages. That being said, I still want to be able to render out the appropriate .aspx page if it exists in my code.
For example, when a request is made to the site, I want to check and see if that URL is in the database, if it is, then I want to render the content appropriately. However, if it doesn't, then I want it to continue on to rendering the real .aspx page.
In trying to use an HTTPModule, I cannot get the page that exists in the database to write out the appropriate content. Here's my code.
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
Uri url = application.Context.Request.Url;
//Checks to see if the page exists in the database
PageInformation page = PageMethods.GetPageFromUrl(url.AbsolutePath);
if (page != null)
{
string renderedPage = Renderer.RenderPage(page);
application.Context.Response.Write(renderedPage);
}
}
However, when trying to use an HTTPHandler, I can't get the real .aspx pages to render appropriately because the *.aspx verb is being dealt with by the handler.
If anyone has any better ideas on how to completely re-design this, I'm completely open to that as well. Thanks.

This will do the trick:
Type page_type = BuildManager.GetCompiledType ("~/page.aspx");
Page page = (Page) Activator.CreateInstance (page_type);
page.ProcessRequest (Context);

I think you're lookign for a simple URL rewriting example.
So you have a single page "default.aspx" that could take an argument of the content you want to display "default.aspx?page=home", but you don't want the nasty query string part "?page=home".
this is best solved by URL rewriting which can be used as an ISAPI module in IIS. So instead of the URL string above, people see a page called "home.aspx", and the web server translates this into "default.aspx?page=home" for your page which can go get the content for the "home" page out of the DB and display it on the screen.
Here's a page with more information on a good implementation of this process:
http://www.opcode.co.uk/components/rewrite.asp

I believe this shows how to process the "normal" pages inside a handler
other example

Related

Is it possible to dynamically load an .aspx page?

I received a new requirement today: For our product page, they want a completely different layout to be used based on the product type.
For example, say we sell buckets. Currently, all buckets use the exact same page layout. But now, they want wooden buckets to use the current layout, and plastic buckets to use a completely different layout. However, they want the URLs to stay the same (e.g., domain.com/bucket/1), so I can't just forward plastic buckets to a new page.
The current page structure is as follows:
CurrentMasterPage.master > CurrentProductPage.aspx > Several UserControls
The new layout requires new pages (i.e., none of the current ones are reused):
NewMasterPage.master > NewProductPage.aspx > Several UserControls
My first thought was to take all of the markup and code from CurrentProductPage.aspx and put it into a UserControl, then create a second UserControl for the new layout (NewProductPage.aspx), and have CurrentProductPage.aspx dynamically load the appropriate UserControl based on the product type, however, this doesn't work because the new layout requires a new MasterPage, and I can't reference a MasterPage from a UserControl.
Then, I thought about using URL Rewriting, but I don't think it's possible to have the same URL load two different pages.
Is there any way to accomplish this?
Why not use a 100% server side re-direct?
When you use response.Redirect("some different page"). Then the client side browser is sent a whole new copy of that page, and the URL will be updated.
However, the server side can write any page it wants to. The client side will not even know the server decided to dish out a different page for the given URL.
So, you could have a page with fake tabs as buttons. When the user hits a button, the browser round trip starts (for the given URL). But on server side, you can then dish out a different page for that URL.
So, in place of this classic "round trip", you can use:
Server.TransferRequest("MyotherWebPage")
So, for the given URL, before the current page (based on given URL) is sent down back to the browser, the above will simply pump out a different page. The current page will never make it back down to the browser.
In fact for a rich page with lots of buttons and features, you can change the page displayed. So in on-load - simply in place of a "response.Redirect", use a server.Transfer. The current page never makes it to the client - the one you dish out where. Because the client side has zero clue about what the web server decides to dish out - it will also have zero clue that a different page was send back to the client.
Try the above with a test page.
On page A, behind a standard button, jump to web page B
eg:
Response.Recdirect("MyPageB.aspx")
Note the URL change - classic round trip.
Now, do this with the button:
Server.Redirect("MyPageB.aspx")
In this case, no full round trip occurs. The server transfers directly to the new page and sends that out. (and note how your URL does NOT change).
You can change the Master Page on PreInit on the Page using a Master. This is possible because a Master is basically the same as a User Control and is loaded AFTER the page's code behind.
protected void Page_PreInit(object sender, EventArgs e)
{
if (NewProductPage)
{
MasterPageFile = "~/NewMasterPage.master";
}
}

Adding search parameter to url to enable direct search from address bar

I have a few old sites that I want to add routing parameters. They were coded without using mvc so there are no global.asax with the handy MVC settings.
Currently I have a page with the url abc.com/xyz that has a search function. I can input a query which would send me to another page but it has the same url. I want to make it so that if i put some variation of the url abc.com/xyz?search='what_You_Query', it gives me the searched page. Right now that url sends me to the page where I input my query.
The website is coded in C# and html and saved in aspx files. The webpages also make use of jscripts
I'd appreciate any help I can get
Edit: Seems like there was some confusion, there is a search box that allows the user to query on the webpage. What I want is to allow users to directly link to a searched page.
You'd need to capture that on the page load - check the query string (https://msdn.microsoft.com/en-us/library/ms524784%28v=vs.90%29.aspx) and if search is in it, redirect to the search page.
MODIFIED TO INCLUDE MORE DETAILS
I'm assuming your working with web forms (Microsoft alternative to MVC). You would need to add a server-side (http://www.seguetech.com/blog/2013/05/01/client-side-server-side-code-difference) Page_Load event (https://msdn.microsoft.com/en-us/library/6w2tb12s.aspx). There the code would look something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString["search"] != null)
Response.Redirect("/search?" + UrlEncode(Request.QueryString["search"]), true);
}
Please note I have not tested the code and am going by memory a bit here - but that should do the trick.

Call aspx, html pages from another aspx page

I have one aspx page where I want to display contents of another aspx or html page based on the sessions. Code behind logic will fetch the file from particular location based on the session. I do not want to use frames, iframes because I have to make sure of cross browser compatibility. Is there any other way to achieve this?
User control may be a solution for this. I wanted to know more alternate approach.
Below is my code:
I don't have anything in aspx except the references to the external js file.
Code behind:
private void Page_Load(object sender, System.EventArgs e)
{
_getMainMenu();
}
protected string _getMainMenu()
{
string HomePageMenu = string.Empty;
string homeExist = Server.MapPath("../homepages/" + Session["ACCOUNT"].ToString() + "/HomePage.htm");
if (File.Exists(homeExist ))
{
HomePageMenu = "../homepages/" + Session["ACCOUNT"].ToString() + "/HomePage.htm";
}
else
{
HomePageMenu = "../homepages/NewMenu.html";
}
return HomePageMenu ;
}
Thanks.
Sounds like maybe something like jQuery load is something that may be helpful. This will asynchronously retrieve content and place it into a control of your choice, and not necessarily an iframe of course. This is called from the client, but you can have your server side logic/session state determine the content returned.
You should change the way you manage your content in generally.
In your case, your aspx-page is your content. And if you want to show contant b in contant a, you will have to show an aspx-page inside another aspx-page.
Change the point of view: your aspx-page should only be your content-holder. Extract your content to an ascx-usercontrol or store it in a database.
Then you are able to fetch the content whereever you need them.
Showing an aspx-page inside another is a very bad solution.
But if it's not possible to change the way your content is stored: I would prefere an iframe.

ASP.NET Web Forms - How to redirect and pass parameters without problems

I wanted to redirect (by code) to another ASPX page and on that page I wanted to select the appropriate view (in a multi-view and during page load).
My solution was to add a url parameter that was checked on the "OnLoadComplete" event and take appropriate action, but it seems that this url parameter gets copied to all the links on the page. So, the user cannot navigate anywhere else because always this view gets presented.
My second thought was to use a Session variable, but I am afraid that this will be an overkill.
Any ideas/thoughts/suggestions on this matter?
Can I prevent the use of the url parameter in all the page-links?
Is it bad if I use a Session variable for this temporarily?
Is there some other way to do this?

Passing objects to a different page using asp.net

I am trying to pass an object from one page to another page using <asp:hyperlink> without any success. I was trying to invoke a C# method and put that object into a session but then I realized you can't invoke a method using <asp:hyperlink>. Then I thought about using <asp:linkbutton> but then I need to open the new webpage in a new window.
How can I go about doing this properly? Are there any other good alternatives?
Then I thought about using <asp:linkbutton> but then I need to
open the new webpage in a new window.
You do not need to open a new window... add this to your server side LinkButton handler:
<asp:LinkButton id="btnYourLinkButton" runat="server"
OnClick="btnYourLinkButton_Click">Test</asp:LinkButton>
protected void btnLogout_Click(object sender, System.EventArgs e)
{
var someObject = GetYourDataWithSomeFunction();
Session["YourData"] = someObject; // saves to session
Response.Redirect("yourNewUrl.aspx");
}
This will store the value in the Session and redirect to a new page in the same window.
EDIT:
If you need to open in a new window then do the same thing as outlined above but instead of doing a Response.Redirect add the window.open javascript call to your page that is served up to open the new window:
ScriptManager.RegisterStartupScript(this, this.GetType(), "AUTOOPEN",
"window.open('yourNewUrl.aspx', '_blank');", true);
Optionally you could just add an ajax call to your click method to setup the Session server side and then trigger the redirect based on your ajax call complete.
Add the object to the Session then redirect to the new page. In the new page, check the Session variable for the object.
Any web application tends to be stateless in nature. Your objects only live during the processing of the page request. When developing and appliction with a technology such as ASP.Net the general pattern for object retrieval is to send an identifier as part of the form post data or the querystring and then use this identifier to reload the object that you were working with prior to the previous page post/request.
It is possible to add objects to the session and retrieve them as suggested in other answers here, but there are issues with this approach e.g. sessions timing out, scalability etc.
If you were to give some more details as to the nature of what you are trying to do it would be easier to give you a more complete answer or suggestions on how to solve your particular problem.

Categories

Resources