Submit a form from code behind - c#

I'm having trouble implementing a functionality on my c#/asp.net app.
I have a form with a RadioButtonList and a submit button.
The RadioButtonList is generated on Page_Load() from a list of objects I retrieve from the database.
I would like to automatically submit the form if there is only 1 object in the list.
I have access to my Form object, to the submit button etc... but I can't seem to find a solution (in the end I'm looking for a kind of form.Submit() ) method.
Does anyone have an idea of how I could do this ?
Thanks in advance !
EDIT >> Here is the code :
.aspx : http://pastebin.com/0E6T7dqH
.aspx.cs : http://pastebin.com/54payZJP
EDIT2 >>>
As it seems there is no way to do what I wanted to do at first, I ended up using a session variable with a response.redirect()
Source :
http://dotnetslackers.com/Community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx

Post happens in the client side. As in Page_Load you are currently executing in the server side, just call the code you want to execute on post.
Edit: For actually going to another aspx
public void Page_Load(object sender, EventArgs e) {
if(!IsPostback && OnlyOneItem) {
Server.Transfer("TheOtherPage.aspx");
}
}
Server.Transfer will maintain the entire request, so your post data will be available.
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer.aspx

Try something like this
In your Page_Load
if(!IsPostBack)
{
if(check for only one object)
{
//your submit code
}
}

I actually had to do something similar, once. Here is a way you can do it.
Asp.Net buttons have a property called PostBackUrl, and it does exactly what you would expect - it controls where the form will post if you click the button.
You can also use the RegisterStartupScript function to render javascript on the page.
Now, with these two pieces, you can achieve your goal.
if(!IsPostBack)
{
if(results == 1)
{
button.PostBackUrl = "next page's url"
//Register script to click the button using RegisterStartupScript
}
}
Now, having shown you this, I will warn you it may not make for the best user experience. When I did it, it was for a very specific case that had no other solution. The page will actually post back to the user, and they will see the page for a moment before the javascript to click the button takes effect. Additionally, when you set a button's PostBackUrl, that means that when it is clicked, your entire form will be posted to the page specified. The code behind for the current page will not fire at all, so if you have any validation, it won't run.
There's nothing wrong with letting the user click the button to submit the form even if they only have one choice. In my experience, users like to feel like they are in control on the system; they don't like it when pages just do things without their input.
Also, there is not really anything wrong with putting the information the next page needs into the session or even a database table, and using Response.Redirect. It's a fairly common practice and works reliably in most scenarios.

Related

ASP.NET UpdatePanel: Make browser "back" button return to *last* version of the page

I have page A and page B. You can do the following things in page A:
Do stuff on page A (e.g., choose an item in a list box), which causes an UpdatePanel in page A to be redrawn with additional information.
Move on to page B. This is done with a Button and Response.Redirect.
Now the problem is as follows:
The user does stuff on page A. Page A is now different from its initial state.
The user moves to page B.
The user hits the back button of the browser.
What happens: Page A in its initial state is shown.
What I would like to happen: Page A in its final state is shown (i.e., with the "correct" item selected in the list box).
I know about ScriptManager.AddHistoryPoint! As far as I can see, it does not solve my problem:
I could call AddHistoryPoint every time something is done on page A. This is bad, because it litters the browser history with lots of entries. (A new entry every time a different list box item is selected.) But that's exactly what I want to avoid by using an UpdatePanel! Of course, if there were a ReplaceLastHistoryPoint method, that would be perfect, but I did not find one...
I tried to call AddHistoryPoint right before Response.Redirect, to save only the last state of page A, but, alas, that doesn't work (no history point is saved). This is not surprising, considering how Response.Redirect works.
Is there some solution I have missed? I'm using .NET 3.5SP1, in case it matters.
This is a bit of an old question, but I'll go ahead and provide the mechanism I use for this. The basic idea is that instead of allowing AddHistoryPoint to manage your name-value pairs, just allow it to manage a key to your NameValueCollection that you keep somewhere else, like in your Session cache. Then as subsequent Ajax requests come in, you never make another call to AddHistoryPoint; instead, you just replace your NameValueCollection with the state of the current request.
The only other bit is to keep track of whether you're on your first Ajax call and need to make that first call to AddHistoryPoint or not.
My code looks something like this:
protected void Page_LoadComplete(object sender, EventArgs e) {
if (!ScriptManager.GetCurrent(this).IsNavigating && (IsCallback || IsInAsyncPostback())) {
var state=new NameValueCollection();
//OnCallbackHistory(state); // this gets state for all interested parties
if (state.Count != 0) {
string key=ViewState["HistoryStateKey"] as string; // empty on first AJAX call
if (string.IsNullOrEmpty(key) || ScriptManager.GetCurrent(this).EnableHistory) {
key=CallbackHistoryKeyRoot+Interlocked.Increment(ref callbackHashKey).ToString();
ViewState["HistoryStateKey"]=key;
ScriptManager.GetCurrent(this).AddHistoryPoint("", key);
}
Session[key]=state;
}
}
}
Instead of calling AddHistoryPoint on the server you could call addHistoryPoint on the client using the Sys.Application class, http://msdn.microsoft.com/en-us/library/vstudio/cc488025(v=vs.90).aspx.
So you'd add a client side click listener to the button which would addHistoryPoint on the client before the button does the post back and redirect.

Call an event handler on another page

Simple question here, but I've got a nagging feeling that there's a more interesting solution than the one I've chosen:
Page Two consists of a dropdown, and the change event is handled to execute some query.
protected void ddlSavedQueries_SelectedIndexChanged(object sender, EventArgs e)
{
/* stuff happens */
}
Page One is a home page, where I'm providing another version of that dropdown. I'd like the change event in this case to redirect control to Page Two, and then execute the event handler.
My cheap solution is just a Redirect with a querystring value that is handled on page load. Am I missing a more interesting approach?
If you don't want to ugly things up with a querystring value, I suppose you could put something in Session and pick it up on Page_Load of the second page (and then clear it out of Session). Not exactly an awesome improvement though.
Does the same page always get displayed when you change that dropdown? If so, consider using client side javascript to redirect to the correct page, then fire any logic on the subsequent page in the page_load event. Example using jQuery:
$(function() {
$("select.classyouneedtodefine").change(function() {
document.location.href = "somepage.aspx?value=" + $(this).val();
});
});
haven't tested the above...just shooting from the hip

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.

URL and Query management Asp.Net C#

Ok so while back I asked question Beginner ASP.net question handling url link
I wanted to handle case like this www.blah.com/blah.aspx?day=12&flow=true
I got my answer string r_flag = Request.QueryString["day"];
Then what I did is placed a code in Page_Load()
that basically takes these parameters and if they are not NULL, meaning that they were part of URL.
I filter results based on these parameters.
It works GREAT, happy times.... Except it does not work anymore once you try to go to the link using some other filter.
I have drop down box that allows you to select filters.
I have a button that once clicked should update these selections.
The problem is that Page_Load is called prior to Button_Clicked function and therefore I stay on the same page.
Any ideas how to handle this case.
Once again in case above was confusing.
So I can control behavior of my website by using URL, which I parse in Page_Load()
and using controls that are on the page.
If there is no query in URL it works great (controls) if there is it overrides controls.
Essentially I am trying to find a way how to ignore parsing of url when requests comes from clicking Generate button on the page.
Maybe you can put your querystring parsing code into IsPostBack control if Generate button is the control that only postbacks at your page.
if (!IsPostBack)
{
string r_flag = Request.QueryString["day"];
}
As an alternative way, at client side you can set a hidden field whenever user clicks the Generate button, then you can get it's value to determine if the user clicked the Generate button and then put your logic there.

ASP.Net: Page_Load() being called multiple times

I don't know alot about ASP.Net but I'm trying to make a new control for a message box. You enter some info and press a button.
However, for some bizarre reason when the button is pressed, Page_Load() gets called a second time, and all of the member variables are reset to null! I need those variables, and Page_Load() has not reason to be called a second time! Of course the callstack is useless.
Remember, in ASP.Net every time you cause a postback of any kind, including handling events like button clicks, you're working with a brand new instance of your page class that must be rebuilt from scratch. Any work you've done previously to build the page on the server is gone. That means running the entire page life cycle, including your page load code, and not just the click code.
Always two there are, no more, no less. A request and a response.
When the page posts back, the Page_Load method is called. Then, once the server actually processes the page and sends you a new one based on changes, the Page_Load is called again, actually the first time on the new page sent to you.
So if you are pulling data in the Page_Load event or setting some values, enclose it in the following block:
if(!Page.IsPostBack)
{
}
to preserve some of your state. Otherwise, the instructions that you put into the Page_Load event will execute every time.
It helps to review the ASP.Net page lifecycle :)
As Joel mentioned, instance variables will be lost once the page is sent back to the client. However, there are various methods of storing the values of your variables so you can retrieve them later. This page on State Management is a good starting point if you want to learn more.
Any tag/element which requires url reference like img, anchor, object etc must be checked for the empty reference.
e.g. href="", url="", src="" are some common errors.
This code works for me:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["something"] == null)
{
Session["something"] = "1";
}
else
{
Session["something"] = null;
//your page load code here
}
}
}
For me, the issue was a bit complicated, but I found that the
protected override void OnPreRender(EventArgs e)
handler is only called once, so it's safer to put some actions in there if it's not too late in the pipeline for you.
An extension of #user3207728's response, I found this link explains it well and has a simple solution...
http://www.aspdotnet-suresh.com/2010/04/detect-browser-refresh-to-avoid-events.html
Unfortunately checking just for if (!Page.IsPostBack) is not enough as IsPostBack will always be FALSE on a refresh.
Just a shot in the dark but maybe add this after your page_load:
if (!IsPostBack)
{
you can use sessions or viewstate to retain the values of variables..
if you want to redirect to a different page , use session[]
else if you want to stay on the same page , use viewstate[]
In my Case the Problem Was Related to Iframe, One Time I removed the Iframe Everithing Work Fine
<iframe id="pdf2"
src="#"
width="100%"
height="100%">
</iframe>

Categories

Resources