Passing objects to a different page using asp.net - c#

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.

Related

How to get a Page from a class in asp website

sorry for my bad English.
I have a Default.aspx page in my project containing a textbox and a button. So when the client clicks on the button, the browser calls a method that is in my web service WebService.asmx.cs whit the textbox.Text as parameter.
(e.g NameSpace.WebService.Say("Hi"); in js)
But I need to report the results ("Hi") to my Default page for showing them in an UpdatePanel and I don't know how to get the page.
I tried (Default)HttpContext.Current.CurrentHandler but it was null.
Is there any other way to get that page?
You can't access the Page object while calling a static(webmethod) method. Static methods cant access instance of the Class it is part of.
Options you have are:
1. Save the value in Session. (HttpContext.Current.Session should be accessible) and show it on the next page load, after accessing it from session. This is a roundabout way and you will have to decorate the webmethod with this attribute:[WebMethod(EnableSession = true)]
2. Instead of using webservice, just update the label in Client side itself using Javascript.

Remove content of asp.net session while navigating onto another page

I have a session variable that I am using on a page. I know that sessions should be used for the purpose
of storing data between different pages of a website, but I have a big dataset to store and I am using a session instead of a view state.
I would like to empty the session when I navigate to another page.
Is there a way I can do it ?
I tried setting the session variable to null on the PageUnload event, but thats not what I want.
I would like to set the session variable to null while the page is navigated to another page.
Please let me know.
You just need to call
Session.remove("nameOfSessionVariable") ;
And regarding to how to handle the "leaving page event"
You will have to write some front-end javascript to do this using
something like window.onbeforeunload(). Then you'd have to make an
AJAX call to tell your back-end that this event is happening. This
isn't foolproof, of course. A browser crash or a forced "quit" would
not fire this event.
As can be seen here C# ASP.NET Page Leaving event?
If you truly want to detect when user leaves the page - you have to do this from the client-side. Handle onbeforeunload event and make an AJAX call to clear session variable.
But this is an overkill. Consider refactoring the code to store in session smaller amount of data and only that is used between different pages.
On the page you have navigated to you can clear a session variable as follows:
Session.Remove("Name");
To abandon the session completely:
Session.Abandon();

call clientside javascript from asp.net c# page

I have a c# asp.net page and an update function which will update the database. In this function I would like to call some client side javascript. I've read a lot about registering a start up script in page_load() but this is always trigger on page load (funny that!)
How would I register then call a script inside my update function? Triggered when a user clicks the "update" button. I have tried the following (inside my function)
protected void doUpdate(object sender, EventArgs e) {
string jScript;
jScript = "<script type=text/javascript>alert('hello');<" + "/script>";
ClientScript.RegisterStartupScript(GetType(), "Javascript", jScript);
}
but it isn't fired. Any ideas? Many thanks.
[update]
It's now working - the function looks like this
protected void doUpdate(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this, GetType(),"Javascript", "cleanup();",true);
}
Cleanup() is the javascript function in my HTML. Thanks for the help guys :)
If the control causing the postback is inside an UpdatePanel you need to use
ScriptManager.RegisterStartupScript
You can't 'execute' client side scripts from the web server (the client knows who the server is, but not the other way around).
The only way to overcome this limitation is by a. create a long-polling process that requests something from the server, the server doesn't complete the request till it has something to return (then client side it makes another request).
What you are really looking for is websocket (duplex) enabled communication. You can check out alchemy websockets or SignalR (has a pretty nice library with dynamic proxy generation).
The reason why that 'script always works on Page_Load' is because it effectively injects your script tag into the html returned for the page requested.
Your Update button is likely using the standard ASP Button behavior, meaning it is type="submit" when it is rendered. Since that's the case, you can just use:
Page.ClientScript.RegisterOnSubmitStatement
Keep in mind that will register a script for every postback, not just the Update button. So, if you only want some javascript run on clicking Update, you would need to check if the EventTarget is UpdateButton.ClientID. Also, RegisterOnSubmitStatement always adds the <script> tags, so don't include those in the javascript statement.
An even easier solution, the ASP Button itself also has an OnClientClick property. This will run client-side code (javascript) when the button is clicked in the browser.

Dynamic Pages From a Database in 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

How do I HTTP POST from an ASP.NET button?

Sorry, another super basic ASP.NET question. this so embarrassing.
I am reading the article on How to: Pass values between ASP.NET pages
In the second approach, they suggest hooking up a button and directing the user to another page using POST. I don't know how to do this. How do I HTTP POST?
"When the source page uses the HTTP POST action to navigate to the target page, you can retrieve posted values from the Form collection in the target page."
This is how I am sending the user to the new page:
protected void btnSubmitForPost_Click(object sender, EventArgs e)
{
Response.Redirect("GetViaPost.aspx");
}
EDIT
The final solution:
You can use ASP.NET webforms. Do the following: On the first page, create your controls and a button that sends the user to a new page. Handle the click event from this button. As stated below, use Server.Transfer with endResponse=false, instead of Response.Redirect(). When you use Response.Redirect, your post data is cleared out. I did not need to specify action in the form or anything else.
In ASP.NET when you click a button, you're posting the entire page's fields by default (as it's contained within a gigantic <form /> tag last time I checked. You can access these values after clicking the button like this:
string MyPostedValue = Request.Form["MyFormField"];
*Edit as per your update in your question, change Response.Redirect() to Server.Transfer() like this:
protected void btnSubmitForPost_Click(object sender, EventArgs e)
{
Server.Transfer("GetViaPost.aspx", true);
}
Then in your GetViaPost.aspx's page you can get any form/query string variable you passed from your sending page like this:
string MyPostedValue = Request.Form["MyFormField"];
If I'm reading this right, all of these answers are missing the question...
You're looking at posting from one Asp.Net form to another, and one of the methods is what you want to figure out - doing a normal http post. The book or article probably is already telling you about the Server.Transfer as another option if I'm guessing right.
If I'm getting the question right, then the simplest answer is to not use a standard ASP.Net form (with the runat = server attribute) as the starting point, but to use a simple standard html form to post to an asp.net page
<form action = "targetpage.aspx" method="post">
...some form fields here
<input type = "submit">
</form>
If in the codebehind you wire up to the button click event, then click the button. It's a POSTback that happens.
Any controls that you have runat="server" will be accessible by their id (and any values set on them) in the codebehind.
In terms of posting data to other pages, you have a number of options available to you.
The querystring, sessions, cookies and viewstate.
A basic example (with no error handling) given your updated Response.Redirect might be:
int someId = int.Parse(txtBoxOnThePage.Text);
Response.Redirect(string.Format("GetViaPost.aspx?myId={0}", someId));
Then on the GetViaPost page you could pull that out by:
HttpContext.Current.Request.QueryString["myId"]
http://www.asp.net/learn/ is a surprisingly good source of information and tutorials for this kind of learning.
ASP.NET buttons always perform a POST. You can set which page the button posts to using the PostBackUrl property of the button. If you leave this blank, the button will post back to the same page that is resides on.
Check out this article for more information.

Categories

Resources