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
Related
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
}
I have the following project :
It's a page that on Page_Load it fills a TextBox named Email and a TextBox named UserName with a value obtained from asking a database.
Then there is this button, if the email is not null(user is not registered) it will let you register, otherwise it will let you change the email linked to your username.
The thing is, when trying to modify the email, doing an update query, the page preloads, taking the new value placed on Textbox Email the same that is retrieved from the database, making so it will never change.
I've tried to see if it executes the query and it does.
I've tried everything, keeping the variable on a hidden label, creating two different buttons with no luck as when it reloads the code those values are empty again.
I was thinking if I could keep the variable somehow that isn't cookies.
I think You know What is happening.. On every Post back the Page_Load event resetting your Textbox Value
Use IsPostBack to bind the value only on 1st load of page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind dropdown and fill textbox here
TxtName.Text = "Your values";
GetDropdowns();
}
}
I hope this will solve your issue
I totally agree with Kanis XXX, you can use IsPostBack to fill the values only at the start page, and not on other postbacks. In my experience, there are some other advices for your problems:
Using Viewstate, Session state,... to keep your working variable. You can have more detail here: https://kimphuc.wordpress.com/2009/10/18/the-difference-between-viewstate-sessionstate-cookies-and-cache-in-asp-net/
Try to use UpdatePanel, this could be useful in some cases, let you refresh or update data just a part of your page, not the whole page. https://msdn.microsoft.com/en-gb/library/bb398864%28v=vs.100%29.aspx
I'm writing code to read data from asp controls to update records in a database. I've been debugging the last day and I've tracked it back to something that I ought to have noticed before.
The code first populates the controls with the existing values from the database.
When I click SAVE, it should read the current values from the controls and save with those.
Unfortunately, what it's actually doing is using the values of the controls before a change was made to them. It's not seeing the change to the controls.
Here's a sample:
<asp:TextBox ID="OtherCourseName_5" runat="server"></asp:TextBox>
Here's the corresponding behind code in the btnSave_onClick() function:
int object_number=5;
string other_course_name_string
= "OtherCourseName_" + object_number.ToString().Trim();
TextBox ocn = utilities
.utils
.FindControlRecursive(this.Master, other_course_name_string) as TextBox;
I'm using the FindControlRecursive() I found somewhere on the web. It works, I'm sure, but just in case, I tried to address the control directly as OtherCourseName_5.Text.
Even if I just display the value in OtherCourseName_5.Text, it gives the original value.
I use this same page for both entering new data and for editing data. It works fine when I enter the data. That is, it correctly sees that the TextBox control has changed from empty to having data. It's only when I invoke the edit function on the page (by passing edit=true). I invoke it this way by adding the switch edit=true as a query string (the program correctly reads that switch, gets to the appropriate area of code, prints out all the correct values for everything - except the contents of the controls!).
The page is far too complicated to post the entire thing. I've tried to convey the essential details. It's entirely possible that I've made a simple coding error, but it's seeming more a possibility that I fundamentally misunderstand how pages are processed.
Is there anything known that can make it seem as though the value of a control has not been changed?
Note 1: I thought perhaps I had to go to another field after I entered the data, but I tried that and it's still a problem.
Note 2: I'm using both TextBox and DropDownList controls and have the same problem with both.
Note 3: These controls are on a panel and the page is using a SiteMaster. I haven't had any problem with that and don't think the problem is there, but I'm down to questioning the laws of the physics at this point.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate controls with data from database
}
}
When you do a postback before the postback handler is evaluated the PageLoad event is raised
so if you don't avoid to rebind your control they will be loaded with the values from the database. And then the postback event will save them to db
Asp.net Page Lifecycle
(source: microsoft.com)
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.
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.