Why label's value is changed? - c#

I know even if the ViewState is disabled for the TextBox, we are not losing the data because it implements the IPostBackDataHandler interface.
<asp:TextBox ID="TextBox1" runat="server" EnableViewState="False"/>
But my question is why this happens for label too? Why label is not losing it's data even if the ViewState is disabled since the label doesn't implements the IPostBackDataHandler interface?
<asp:Label ID="Label1" runat="server" EnableViewState="False" ViewStateMode="Disabled"/>
TextBox definition:
public class TextBox : WebControl, IPostBackDataHandler,
Label definition:
public class Label : WebControl, ITextControl
My code:
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" EnableViewState="False" ViewStateMode="Disabled" Text="Before click"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" EnableViewState="False"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_OnClick"/>
</div>
</form>
And code behind:
protected void Button1_OnClick(object sender, EventArgs e)
{
Label1.Text = "Changed.";
}
I expected to see the "Before click" in my label after I clicked the button but I see the "Changed" text in my label after I clicked the button.

Ok I deleted my previous answer, I will try to re-state it with an example.
First, as others stated, the idea of ViewState is to hold the state between postbacks, rather than during a single page load cycle, so what you're seeing is the expected behavior.
To see the difference with an example, try adding your label with 2 buttons:
<asp:Label ID="Label1" runat="server" EnableViewState="False" Text="Before click"></asp:Label>
<asp:Button ID="btn1" Text="Click" OnClick="btn1_Click" runat="server" />
<asp:Button ID="btnReset" Text="Reset" OnClick="btnReset_Click" runat="server" />
Where btn1 sets the value to "Changed", and btnReset has an empty handler.
Now with EnableViewState set to False, if you click on btn1 the page reloads, btn1_Click is executed, and the page is rendered with the label value = "Changed", if you click btnReset the page will reload again, but since view state is disabled, the label will revert to its original text "Before click"
If you set EnableViewState to True on the lable and click btn1 then btnReset, the label value will stay as "Changed", since the state is kept during postbacks
Hope that clarifies things a bit

This is going to be long and detailed.
Let's start with this markup. Almost identical to yours, with one additional button and a label. I'll explain why we need them later.
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" EnableViewState="False" ViewStateMode="Disabled" Text="Before click"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" EnableViewState="False"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_OnClick"/>
<asp:Label ID="Label2" runat="server" Text="Blah" />
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_OnClick"/>
</div>
</form>
And we'll use this code behind. Again, I'll explain the purpose of the second handler later on:
protected void Button1_OnClick(object sender, EventArgs e)
{
Label1.Text = "Changed";
}
protected void Button2_OnClick(object sender, EventArgs e)
{
Label2.Text = Label1.Text;
}
Let's see what happens when we initially load the page. First ASP.NET reads all the markup, and then goes through the page life cycle with all the events. In markup parsing stage Label1 gets assigned text Before click, and it is never changed later during initial load. So later during rendering phase this is what is getting rendered into HTML and sent to browser. Thus Before click is displayed on the screen. Nice and easy.
Now we click Button1. Postback occurs, which is a term that describes a request sent to the same page by one of its controls after it was initially loaded. Again, everything starts with ASP.NET parsing the markup, and again Label1 gets assigned text Before click. But then page life cycle events happen, including control event handlers. And in the handler for Button1 the text of Label1 is changed to Changed. Now here is the important thing to note: if ViewState for the Label1 was enabled, this new value would be stored in there, and so called tracking would be enabled for property Label1.Text. But ViewState is disabled, and so the new value is not stored anywhere except Label1. Next comes the rendering page stage, and since Label1.Text still holds the value Changed this is what is rendered into HTML and sent to the browser to display. Note however that this new value is not sent inside the ViewState field. As you can see, whether ViewState is enabled or not plays no role in what is displayed after this postback.
Now we'll click Button2, which would trigger another postback. Again, ASP.NET parses the markup, again Label1 gets text Before click. Then comes ViewState loading part. If ViewState for Label1.Text was enabled, it would load changed value into this property. But ViewState is disabled, and so the value stays the same. Thus, when we reach Button2 click handler, the value of Label1.Text is still Before click, which is assigned to Label2.Text. But Label2 has ViewState enabled, and so this new value for its text is stored in ViewState and sent to the client (ViewState is implemented as a hidden field on the client side). When everything gets to the browser, we can see Label1 and Label2 both displaying Before click.
And to nail it down we'll do a third postback, now clicking Button1 again. Just as during the first postback, Label1 ends up with Changed text. But what about Label2? Well, this one has ViewState enabled, so during initial markup parsing ASP.NET assigns it the value Blah, and during ViewState loading it replaces this value with Before click. Nothing else affects this value during the page life cycle (we did not click Button2 this time), and so we end up seeing Changed and Before click in the browser.
Hopefully it makes it clear what the ViewState is for and what disabling it does. If you want to dive even deeper into how ViewState works, I would greatly recommend this article: TRULY Understanding ViewState.

I think you have wrong understanding what ViewState is.
Data in ViewState is being stored BETWEEN requests, but not DURING page lifecycle.
BTW - ViewState data is generated after PreRenderComplete event in SaveStateComplete event.
https://msdn.microsoft.com/en-us/library/ms178472.aspx
If you have ViewState switched off - just think that it will not be generated in output.
During page lifecycle all data assigned to controls(and also to page fields and properties, as the page is just a class) will be rendered as you defined in aspx. But will be lost after, unless is saved in ViewState.

Related

ASP controls need Double-Click to get focus due to OnTextChanged Event

I got a situation here.
I have around 5 ASP controls in my page including some Text-Box and Radio Buttons. These controls are the part of a form where the user will fill data one by one into these controls. Now, the problem is each of these controls have AutoPostBack = True and OnTextChanged or OnCheckedChanged event associated with it.
Here comes the problem. Whenever the user fills one of these controls and try to navigate to the next control, that control needs Double-Click to get focus. It is very inconvenient to double click every control while filling up the form.
I tried to come over the situation by setting Page.SetFocus(<control>); in every OnTextChanged event to the next control in the form. But the same doesn't work in case of a Radio Button. It also doesn't work when the sequence of focus is changed.
I need a work-around to overcome the problem. I can't remove the OnTextChanged or OnCheckedChanged events due to the requirements.
What's actually happening is the page is being posted back and then focus is shifting back to the control that caused the postback. A double click isn't actually strictly happening. The first click causes the first control to lose focus, thus causing the postback. The second click then focuses the control you want after the postback has occurred.
What you can do is capture the control that has received focus prior to the postback and when the page reloads set focus back to that control.
Here's an example (Updated):
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" AutoPostBack="True"
onFocus="SetNextControl(this);"></asp:TextBox>
<asp:RadioButton ID="RadioButton1" runat="server" OnCheckedChanged="RadioButton1_CheckedChanged"
AutoPostBack="True" GroupName="RBGroup" onClick="SetNextControl(this);" />
<asp:RadioButton ID="RadioButton2" AutoPostBack="True" GroupName="RBGroup" runat="server" onClick="SetNextControl(this);"/>
<asp:TextBox ID="TextBox2" runat="server" OnTextChanged="TextBox2_TextChanged" AutoPostBack="True"
onFocus="SetNextControl(this);"></asp:TextBox>
</div>
<asp:HiddenField ID="HiddenField1" runat="server" />
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
if (document.getElementById("<%=HiddenField1.ClientID %>").value != "") {
var controlToFocus = document.getElementById(document.getElementById("<%=HiddenField1.ClientID %>").value);
controlToFocus.focus();
document.getElementById("<%=HiddenField1.ClientID %>").value = "";
}
})
function SetNextControl(e) {
document.getElementById("<%=HiddenField1.ClientID %>").value = e.id;
}
</script>
</asp:Content>
The above sample isn't perfect, I'm not sure if it'll work the way you want with RadioButtons as there is no onFocus event for them. I've changed them to use onClick so that at least focus remains on the last selected radio button. Hopefully this at least get's you a little bit closer to what you want.

Setting a session variable before AutoPostBack fires in an asp:Button

How would I go about setting a session variable from the click of an ASP:Button before an AutoPostBack event fires.
Here is what I have right now, but I'm not exactly sure I'm doing this right:
<asp:Button ID="CommitBTN" runat="server" PostBackUrl="~/MMR_Home.aspx"
onclick="CommitBTN_Click" UseSubmitBehavior="true"
OnClientClick='<% string temp1 = "true"; Session["ClickedFlag"] = temp1; %>' Text="Commit Changes to Database" />
Would this be the correct way of performing this action or am I going at it completely wrong?
EDIT:
Changed my button tag to this:
<asp:Button ID="CommitBTN" runat="server" PostBackUrl="~/MMR_Home.aspx"
onclick="CommitBTN_Click" OnClientClick="document.getElementById('<%= Hidden.ClientID
%>').value='1'" UseSubmitBehavior="true" Text="Commit Changes to Database" />
I receive this as my error:
Microsoft JScript runtime error: Unable to set value of the property 'value': object is null or undefined
Use this:
Inside aspx file:
<form runat="server">
<asp:Button ID="CommitBTN" runat="server" Text="Button" onclick="CommitBTN_Click" OnClientClick="document.getElementById('HiddenField').value='Ram'"/>
<asp:HiddenField ID="HiddenField" runat="server" />
</form>
Or
<script type="text/javascript">
function setMyHiddenField(myValue) {
document.getElementById('HiddenField').value = myValue;
}
</script>
<form runat="server">
<asp:Button ID="CommitBTN" runat="server" Text="Button" onclick="CommitBTN_Click" OnClientClick="setMyHiddenField('Ram')"/>
<asp:HiddenField ID="HiddenField" runat="server" />
==================================================================
Inside aspx.cs file
protected void CommitBTN_Click(object sender, EventArgs e)
{
Session["ClickedFlag"] = HiddenField.Value;
Response.Write(Session["ClickedFlag"]);
}
It is easy to replase "Ram" with your value. ;)
you can change Ram to temp1 easy:
setMyHiddenField('temp1')
Or you can call this function on your another control events befor CommitBTN pressed
Use a Hidden Field control.
Update the Hidden Field to 1 on Button Client Click.
Update the Session Value in the Page Load' event. The Value will be 1 then update the Session variable and set theHidden Fieldvalue to 0 underneath theSession Variable` Update.
Reason for the Usage of Page Load event is that on clicking the Button as per the page life cycle the page events like PreInit, Init, InitComplete, PreLoad, Load executes before the execution of Button Control.
Page events execution takes place like below..
Preinit
Init
InitComplete
PreLoad
Load
Control Event
Load Complete
Pre Render
Hope this will help you...

Session Variable in ASP.NET returns previous value in ModalBox?

I have a question regarding passing Session Variables to a text-box in an Update Panel (which is displayed in a Modal PopUp).
This is the code I have so far:
ASPX CODE:
<asp:TemplateField HeaderText="Link">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Link" runat="server" OnClick="LinkButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="panel_Load">
<ContentTemplate>
<asp:Button ID="OKButton" runat="server" Text="Close" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:ModalPopupExtender ID="mpe" runat="server" TargetControlID="ClientButton" PopupControlID="UpdatePanel1" OkControlID="OKButton">
</asp:ModalPopupExtender>
<asp:Button ID="ClientButton" runat="server" Text="Launch Modal Popup (Client)" style="display:none;" />
CODE BEHIND (C#):
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lbl_nme = (Label)clickedRow.FindControl("lbl_name");
String string_nme = lbl_nme.Text.ToString();
Session["Name"] = string_nme;
mpe.Show();
}
protected void panel_Load(object sender, EventArgs e)
{
Label1.Text = (string)(Session["Name"]);
}
So basically I have a GridView with name, address etc… When the user clicks on a link in a row, then the value for the name field of that row is saved as a session variable. Then a Modal PopUp is displayed. The Modal PopUp should then show the Name which was saved as a Session variable.
The code sort of works. What I’m experiencing is that when I click a row, the Label1.Text in the Modal PopUp is empty. So if I close the PopUp then click another link in another row, the PopUp then displays the Name of the row that was clicked previously.
In other words.. If row 1 has Name “Kevin” and row 2 has Name “Nathaniel”, and I click a link to open the Modal PopUp of row 1, I would expect the PopUp to display “Kevin”. But it doesn’t. The first time I click a link after rebuilding the application, nothing is displayed. But say I click row 2 after clicking row1, then the Modal PopUp displays the value of the row I clicked before, i.e. “Kevin” when I expect it to be “Nathaniel”.
I hope I didn’t confuse anyone. I’m a newbie and I’m just getting into this stuff, so I’d appreciate it if someone could help me out, preferably with examples of code etc.
Thank you. Much appreciated.
The "Load" event (panel_Load) occurs before the "Click" event (LinkButton1_Click) so it only sees the previous value.
The quick fix is to set the label in the "Click" event as well. Unless ViewState is enabled for the label (ick!) the label may have to be [re]set in the "Load" as well, depending upon when/how updates occur.
See ASP.NET Page Life Cycle Overview and ASP.NET Application and Page Life Cycle: Page Events.
Happy coding.

Is this the intended behavior of textbox and label?

I set the value of the controls when the DOM loads. I have this super simple code on aspx page:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=textBox2.ClientID %>').val($('#<%=textBox1.ClientID %>').val());
$('#<%=lblVal.ClientID %>').html($('#<%=textBox1.ClientID %>').val());
});
</script>
<asp:TextBox runat="server" ID="textBox1" Text="Test data" />
<asp:TextBox runat="server" ID="textBox2" />
<asp:Label runat="server" ID="lblVal" Text="Old Data" />
<asp:Button runat="server" Text="Click Me" onclick="Unnamed1_Click" />
In my button click event handler I have this code:
protected void Unnamed1_Click(object sender, EventArgs e)
{
Debug.Write(textBox2.Text);
Debug.Write(lblVal.Text);
}
The thing that came shocking to me lblVal has it's old value. Setting value in javascript doesn't really have any effect on label whereas the textbox2's data is reflected on the server. Is the intended behavior of textbox and label? This came as a bit of surprise to me because I never came across this thing previously.
The label will get rendered to an HTML label tag, not a form field. Therefore it does not have a value that is posted when the form is submitted, and the value you get restored in the postback is from ViewState. Form fields (e.g. a ASP TextBox which becomes an input) will post their value and this will override the value in viewstate.
You could get around this by instead having a hidden input which you update with javascript, and then in your postback update the label with the contents of that instead.
An asp:Label control renders to a span, and is therefore not a form element, and its changed contents will not be posted to the server.

UpdatePanel and Repeater render page unresponsive after post-back

I have a page with an UpdatePanel that contains a Repeater and a text box with the number of items in the repeater. When I change the value, the page is supposed to post back and redraw the Repeater with the updated number of items. This works in principle, but the page ends up frozen after post-backs and does not accept any input - in IE 8 only. It works perfectly fine in Firefox. For instance, the context menu does not appear when I right-click in controls, and I cannot enter text in text boxes.
When I take out the UpdatePanel, the page works fine, but of course refreshes on every post-back event. This is not necessarily related to the Repeater on the page. I think I am seeing this on other pages. What's the trick here?
<asp:UpdatePanel ID="uPanel" runat="server" UpdateMode="Conditional"
EnableViewState="true" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSubmit">
<asp:TextBox ID="tbItems" runat="server" AutoPostback="true"
OnTextChanged="textchanged_Items"/>
<asp:Repeater id="rptItems" runat="server"
OnItemDataBound="repeaterItem_Databound">
<...>
</asp:Repeater>
protected void textchanged_Items(object sender, EventArgs e) {
try {
// this methods rebinds the repeater to a List after changing
// the number of items in the list
ReflowItemRepeater();
// This is not really necessary, since Databind() appears to
// cause an update. I tried it anyways.
uPanel.Update();
}
catch (Exception ex) {
ShowError(this, "Error displaying the item list.", ex, true);
}
}
I ended up removing the update panel.
One month later, different page, I am still and again fighting this. The situation is the same.
An update panel, a repeater (actually 2 nested repeaters), and a control in the repeater that fires a postback event. The server processes the event correctly and returns control, but the browser (IE8) never refreshes the update panel. The page is unresponsive, as if in some sort of dead-lock situation. I can unlock it by clicking on a button that fires another postback event (also in the update panel). But the text boxes in the panel are not clickable or editable when this happens.
Also, it happens only the first time. Once I have "freed up" the lock, or whatever it is, it will not happen again on this page, even when I repeat the exact same steps that led to it.
When this happens, the JIT debugger does not report anything.
I would actually set Triggers within your updatepanel.
I'm not sure you need to call .Update in your code behind as the updatepanel will be updated when the trigger occurs.
Try this:
My gut feeling is that it has something to do with the use of the OnTextChanged event. For kicks, try adding a button next to the text box, and reflow the repeater when the button is clicked instead. Does IE still freeze?
So I stripped this page down to the minimum and I found out what is doing it - the AjaxToolkit:CalendarExtender. If I take it out, everything works fine. Still, I would be curious to know if there is a workaround.
Here is a link to my test page. I will keep it up for a few days.
To see the issue, select "2" from the drop-down, then type something into the first quantity field and tab out. The cursor will blink in the next field, but it does not allow input. This happened in IE8, not in Firefox.
Edit: Actually, when I went back to the full page and removed the CalendarExtender, it was still not working. I do suspect that this issue has to do with controls posting back in the UpdatePanel, but I just can't pin it down. It seems seems to be one of these things where a combination of x things does not work, while any combination of (x-1) things does work.
Regarding the initial question, here's a working sample. I don't know if it's anyhow helpful, but just to make sure...
<%# Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server"><title>Ajax Test</title></head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:Label runat="server" AssociatedControlID="txtTest">
Enter 'fruit' or 'vegetables':
</asp:Label>
<asp:TextBox
runat="server" ID="txtTest" AutoPostBack="true"
OnTextChanged="Handler_Test_TextChanged"
/>
<asp:Repeater runat="server" ID="rptItems">
<HeaderTemplate><ul></HeaderTemplate>
<ItemTemplate><li><%# Container.DataItem.ToString() %></li></ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
<script runat="server">
static readonly string[] Fruit = new string[]
{ "Apples", "Oranges", "Bananas", "Pears" };
static readonly string[] Veg = new string[]
{ "Potatoes", "Carrots", "Tomatoes", "Onion" };
void Handler_Test_TextChanged(object s, EventArgs e)
{
if(txtTest.Text == "fruit") rptItems.DataSource = Fruit;
else if(txtTest.Text == "vegetables") rptItems.DataSource = Veg;
else return;
rptItems.DataBind();
}
</script>

Categories