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)
Related
I have an aspx page of images that, when selected, a popup appears prompting for various information tid bits that I then store the information as data attributes on hidden labels through use of jQuery (i.e. data-id="####", data-difficulty="###", etc.). I acknowledge that this isn't the best way to do it necessarily but I've tried other things (see below) and nothing has worked yet.
I've been attempting, and to no avail, to retrieve the dynamically updated data attributes so the various items can be stored to my local ms sql database. The updating of the attributes works perfectly in that I can view the items being updated properly in Chrome's developer tools. Despite this when I try to pull the same attributes I can see as being updated I'm unable to retrieve the updated values in the code behind and keep getting back the initial values (generally an empty string "").
Here's the implementation on the aspx page:
<asp:Label runat="server" ID="lblSelection" data-id="" data-count="" data-price="" data-difficulty="" CssClass="selected-items" />
and here's the relevant method being called when the "Submit" button is clicked further down on the same page:
protected void SubmitClicked(object sender, EventArgs e)
{
var currentID = lblSelection.Attributes["data-id"];
var currentCount = lblSelection.Attributes["data-count"];
var currentPrice = lblSelection.Attributes["data-price"];
var currentDifficulty = lblSelection.Attributes["data-difficulty"];
if (currentID == null || currentID == "")
{
// stop and throw an informative message to the user
}else{
// keep processing ...
}
}
The trouble is that when I run the project in debug mode and inspect those elements (again, making sure that I can visually see that the attributes are actually updated in the developer tools) they're all the initial value of "". My only guess is that there's some kind of post back issue but I wouldn't think that would happen until my method had been called and fully processed. As a note, I'm populating the images onto the page and updating their attributes already through a sql call based on the id of the item:
<img runat="server" src="" data-id="12345" />
The initial loading all works perfectly so I can clearly set the properties from the code behind fine. For whatever reason though I am unable to pick up the updated attribute values in the code behind after the jQuery updates the label's attributes (following some clicking and whatnot). Any tips or thoughts on this would be greatly appreciated.
What you are trying to do cannot work because:
The value of custom attributes is not posted back to the server (as discussed here).
Even if you set the text of the Label in client code, it would also not be available in the Text property in code-behind. A Label is rendered as a span element in the page, and the content of that type of element is not posted back to the server.
A nice list of properties included in a postback is given in this topic: Which values browser collects as a postback data?
As suggested by mshsayem, you should use HiddenFields. If, for some reason, you want to do it differently, you could use hidden TextBoxes, set their value in client code, and retrieve it with the Text property in code-behind. In other words: HiddenFields are not the only controls for which a value set in client-code can be retrieved in code-behind (but they are the obvious choice if the control is not to be displayed).
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 have got an ASP-Site, which enables the user to Add Label-Elements. I don’t know how many Labels where added or which ID they have. I know only, they will be within the Panel pnl_Added. After the user has added all his labels, he pushes a Send-Button for Update.
So, now I am at my Server, awaiting this postback, but I don’t know where, when and how to find out, which Elements were Added to pnl_Added. Can somebody help me?
I have tried something like that:
protected void Page_Load(object sender, EventArgs e)
{
[...]
for (int i = 0; i < pnl_Added.Controls.Count; i++)
{
[...]
}
[...]
}
But I think it is too late because of the loaded ViewState? Is that possible?
I am working with VS 2013, ASP c#, with the .Net Framework 4.
On server, controls tree doesn't created from actual client HTML. Actually, server doesn't know anything about client HTML besides input tags values in scope of submitted form. In general, all controls available in Page_Load method, created on server side from aspx file markup.
To implement your scenario, you need to add hidden field for each label, added from client and save label's inner text into hidden field's value. Then you'll can get these labels texts as below:
var labels = Request.Form["hiddenField's name"] as string[];
You should go one lever deeper and take the added elements from Request variable, because the control pnl_Added doesn't know about them as there was no postback.
Something like this:
Request.Form["field_id"]
I suggest to run the page in debug mode, review Request.Form collection and find what you need. You should see your label elements there.
I encountered some weird behaviour today and I was hoping someone could shed some light on it for me because I'm perplexed.
I have a couple of methods I use to interact with the ui for the sole purpose of displaying error/success/warning messages to the user.
Here is one of them
public static void Confirm(string text)
{
var page = (Page)HttpContext.Current.Handler;
var uiConfirm = new HtmlGenericControl("div")
{
ID = "uiNotify",
InnerHtml = text
};
uiConfirm.Attributes.Add("class", "ui-confirm");
page.Master.FindControl("form1").Controls.AddAt(2, uiConfirm);
}
This works perfectly fine except for one nuance I encountered this morning and I was hoping someone could shed some light on it for me.
I am working on your run of the mill profile editing page. In this page, I am binding a couple of dropdownlists (country, province/state) on page load. I have a submit at the bottom and a click event that fires to update the information, then call the method above to notify the user that their information was successfully updated. This works the first time you click the submit button; the page posts back, the information gets updated in the database, the dynamically added div gets popped in, confirm message is displayed and all is good. However, if you then click the submit button again, it fails stating SelectedItem on the dropdowns I'm binding in the page load is null (Object reference not set to an instance of an object). The dropdown is actually wiped for some reason on the second postback, but not the first.
In sheer desperation after trying everything else, I decided to take out the call to the confirm method... and strangely enough the error disappears and I can update the information on the page as many times as I like.
If I add a generic control statically to the page I'm working on, and change my method slightly so that instead of adding a generic control to the form dynamically it just finds the generic control on the page, that does no produce the same error.
The problem also goes away if I remove the two dropdowns from the page or just stop interacting with them.
Why on earth would adding a dynamic control to the form wipe my dropdowns on postback?
I think you should consider using the PlaceHolder class in your MasterPage, the AddAt(2, uiConfirm) is going to bite you and probably is:
Markup:
.......
<asp:PlaceHolder id="PlaceHolder1"
runat="server"/>
......
Code-behind:
public static void Confirm(string text)
{
var page = (Page)HttpContext.Current.Handler;
var uiConfirm = new HtmlGenericControl("div")
{
ID = "uiNotify",
InnerHtml = text
};
uiConfirm.Attributes.Add("class", "ui-confirm");
//may need to change depending on where you put your placeholder
Control placeHolder = page.Master.FindControl("PlaceHolder1");
placeHolder.Controls.Clear();
placeHolder.Controls.Add(uiConfirm);
}
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.