Two postback buttons ASP.NET - c#

I have two simple pages. Page 1 postbacks to page 2. I have two buttons that can cause a postback, Confirm and Delete. On page 2 there are two buttons; one saves the passed data, and the other deletes the passed data. What I need to do is have the unneeded button on page 2 set to visible = false. How can I set up different actions based on which button caused the postback?

you could use Query string to indicate the page to show the appropriate button in your second page
ex : http:\localhost\page1.aspx?show=delete
at the other hand, in your page2 "page_load" function you could manage the code to show the button based on query string requested along with the request url
the code will be something like this on your Page_Load:
string showButton = Request.QueryString["show"];
if(showButton == "delete")
{
// write the code to show the delete button here
}

Related

Server.Execute() opens the new page in current page

I used server.execute to hide my query string in URL, but I found another problem, when I'm in page 1 and clicks a button that transfers me to page 2 , page 1 content is still displayed in the page with the content of page 2. Both pages are shown to me. How can I resolve this ?
example of my code. in page 1 , there is a button, I add this code in click event.
protected void Button1_Click(object sender, EventArgs e)
{
Server.Execute("Page2.aspx?Name=john");
}
in page 2 , there is a text box that reads the query string value.
TextBox1.Text = Request.QueryString["Name"].ToString();
I send multiple values in query string but this is just an example. however, page 1 and page 2 contents are both displayed in one page after clicking the button that should transfer me to page 2.
Use Server.Transfer instead of Server.Execute.
Check this out to understand the difference.
Difference between both
When Server.Execute is used, a URL is passed to it as a parameter, and the control moves to this new page. Execution of code happens on the new page. Once code execution gets over, the control returns to the initial page, just after where it was called. However, in the case of Server.Transfer, it works very much the same, the difference being the execution stops at the new page itself (means the control is'nt returned to the calling page).
In both the cases, the URL in the browser remains the first page url (does'nt refresh to the new page URL) as the browser is'nt requested to do so.
As server.execute transfer control back to original page and continue execution of it also, therefor you are seeing output of both pages. To Transfer the request completely use Server.TransferRequest
Page1.aspx : add query string values as NameValueCollection
NameValueCollection nv = new NameValueCollection();
nv.Add("Name","john");
Server.TransferRequest("Page2.aspx",true,"GET", nv);
Page2.aspx : get your values from Request.Header
TextBox1.Text = Request.Headers.Get("Name");

Can i come back to a predefined viewstate of a page after coming back from another page?

What i've got is a Page1.aspx file, on this page i set some check boxes, some drop down values (a search filter page) that post back.
The search page returns to me a list of records (based on what was selected in the search section of this page).
Each record has a link to a "Details.aspx" page
on Details.aspx page i am able to modify values of the record, once done, i would like to get back to Page1.aspx but have Page1.aspx page in the same state that i left it.
By this i mean, i want the filters to be set as they were before the user navigated to the Details.aspx page
How can i do this?
i can not use history.back or history.go(-1)
Here is one way to do it: Put everything in a Session.
Load all the page1.aspx stuff into a class object, then add it to a Session (obviously before you go to the next page). Then when you go back check if that session exists, if it does, load the page using that class.
var myClass = new MyPage1Save
{
// load all the things you want saved
}
Session["Page1"] = myClass;

Label's text appeared nothing when is session over from the first page

I am trying to Session over my Label.Text in the first .aspx page to another Label in the second .aspx page. I retrieve my value from the database and place them in the first Label.Text and want to Session this Label (Which i got the text from the database) to another page linked to the first page. I use this method is because i have a detailed products page (My first .aspx page) which consists of many products and when user click a particular product, it's product name have to be displayed in the second page of the .aspx . My problem here is that when i Session over the Label's text on the first page, the value does not pass over to another page.
My first page's .cs code (code behind):
Session["productName"] = productName.Text;
Response.Redirect("products2.aspx");
My second page's .cs code (code behind - I place this code in page load)
if (Session["productName"] != null)
productName.Text = Session["productName"].ToString();
Have i gone wrong anywhere?
Inorder to make the session not to be expired for a long time, you should follow two steps.
Keep a continous eye on the Session Timeout.
Redirect the session when its about to expire.
The Base Page for Detecting Sessions will explain you every thing you need to do, please refer it once.
your code is totally right..
but my question is are you using ispostback in your page load??
if not then use it like this..because of postback sometimes you can't get values.
then put your code if is not postback
page_load()
{
if(ispostback)
{
}
else
{
//put your code here
}
}

Javascript added input control on .net postback

What I'm trying to achieve/plan, is whereby a page loads with a set of inputs, e.g. TextBox, Radio List etc. Taking TextBox as an example, there is a button for the user to "Add" another textbox to the page (in the same group), e.g. Member1, Member2, Member3 etc etc.
Two questions:
I could add these with Javascript, however the resultant "save" on postback would not get these inputs? If so, how?
The form needs to work without Javascript as well, so postback to dad another control is fine, however if I click the "add" button again, it will only ever add one control.
protected void btnAdd_OnClick(object sender, EventArgs e)
{
holder.Controls.Add(new TextBox { ID = "txtControl1" });
}
You can access the dynamic controls in the postback by name, using the following syntax "Page.Request.Form[""].ToString();". This uses the "name" attribute, not the "id" attribute.
I guess you can have one of these scenarios :
1- to save any new control ( textbox ) data in a session variable .. for example save name and value in which when any post back you can draw then again from this variable
2- If the only post back done from Add button you can do its function without doing post back as in this example http://msdn.microsoft.com/en-us/library/ms178210.aspx

C# .Net variable unexpected re-initialation

So I am experiencing an issue with an .aspx page and some server side code, where I am getting unexpected results.
The goal of this page is simple, there are 5 radio buttons and a button with a server side onclick function. The idea is the user picks 1 of the 5 radio buttons, and then clicks the button. Upon clicking the button I verify (not using form validation, because I wanted a different feel) that a button is checked, and then store the selected option in a database.
Due to the fact that the number of radio buttons may change in the future I decided to try and abstract the number of radio buttons to make it easier on my self to change in the future.
So at the top of my server side code I created a list of possible options.
I then have a registerVote function that takes in a RadioButton object, and a number to grab a setting from the config file. I throw those 2 values into a wrapper class, and then add them to the list of possible options.
Finally when the submit button is pressed, I iterate through all possible options to see which one is checked, and grab its associated value.
public partial class VotePanel : System.Web.UI.Page
{
List<VoteOption> voteOptions = new List<VoteOption>();
public string registerVote(RadioButton newRadioButton, int voteOption)
{
voteOptions.Add(new VoteOption(newRadioButton, voteOption));
return ConfigurationManager.AppSettings["vote_option_" + voteOption];
}
protected void Submit_Click(object sender, EventArgs e)
{
//Check vote
string vote_value = "";
bool someButtonChecked = false;
foreach (VoteOption vo in voteOptions)
{
if (!someButtonChecked && vo.button.Checked)
{
vote_value = vo.movie;
someButtonChecked = true;
}
}
//....
}
}
class VoteOption
{
public RadioButton button;
public int vote_value;
public VoteOption(RadioButton r, int v)
{
button = r;
vote_value= v;
}
}
The code I use in page to add a radio button looks like this
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Vote" style="position: relative; top: 3px;" /><%=registerMovie(RadioButton1,1)%>
Now for the problem I am experiencing. Whenever the submit button is clicked, the list has a count of zero, and looks like it has been reinitialized. I validated that values are being added, by returning the list count in the registerVote method, and objects are indeed being added, but for some reason are not available to the Submit function.
Now variables on a page like this shouldn't reinitialize right? I also tested a string, and it did not reset and was available to the Submit button. What I did was define a class variable string time = DateTime.Now.Ticks.toString(); and displayed that after the submit button was clicked, and the time was always the same reguardless of how many times I clicked it.
So why would my List reinitialize, but not a string? Any ideas?
Keep in mind that your page class will be constructed and destructed for every request - no state will be maintained between each page load, it is up to you to properly recreate state as needed. In this case it appears that your list voteOptions is not being recreated before Submit_Click is called.
You'll have to register all your voting options regardless of whether the page is in a postback or not inside the Page_Load or OnInit handlers of the page. This will reconstruct voteOptions, which will then be accessed when Submit_Click is called.
Take a look at the ASP.NET Page Life Cycle.
The problem seems to be that you are constructing the List<VoteOption> voteOptions at page render then expecting it to still be there on postback. The Page object does not exist past the point that the page is delivered to the browser, so your list of vote options gets disposed of as well when the browser has received the page.
You'll either need to reconstruct the voteOption list before or during Submit_Click on postback, or give yourself enough information in the value of the radio button that you don't need it.
I don't see in your code any place where the list that you are building is placed in memory. I believe you are rebuilding it on each page reload. P.s. might be my reading but you created a function called registerVote and you are calling a method called registerMovie so that might be your problem.
You could place the list in the session and get it back from session.
Personnally I would change the code to
1) Check if the list is in memory and get it. If not in memory call a method to generate it once and then place it in memory.
2) Use a RadioButtonList on your page that you can then bind to your list as a data source.
asp.net is stateless, so every postback (such as clicking Submit) recreates the server-side class. If you want your list to persist between calls, you should save it in ViewState or a Hidden field. Not sure about the string though; what you're describing doesn't fit the asp.net lifecycle.

Categories

Resources