Is this the intended behavior of textbox and label? - c#

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.

Related

Why label's value is changed?

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.

Bind a textbox value in a label box using c# inside a uframe

I have entered a value in text box and click the button the value should bind in a label.
The code must be in c# not in query. There is no database also.how please say the code behind in c#. It is button click event. while click the button the page should post back and bind the data how to bind a textbox value in a label box using c#. The value must bind in postback method.
easy , take a look at the below code:
<asp:TextBox Id="txt1" runat="server" />
<asp:button Id="btn1" runat="server" onClick="Button1_Click"/>
<asp:Label Id="lbl1" runat="server"/>
//in the code behind implement the Button1_Click
protected void Button1_Click (object sender, EventArgs e)
{
lbl1.Text= txt1.Text;
}
It as easy as the following:
LabelID.Text = TextBoxID.Text;
Where LabelID is the ID of your Label control and TextBoxID is the ID of your TextBox control.
You should place this code inside the button click's event.
Update
Please use for your purpose ASP.NET Web Server Controls.
<asp:TextBox ID="textBoxId" runat="server"/>
<asp:Label ID="labelId" runat="server"/>
Then you can access the values of Text property of both the above controls, like above:
labelId.Text = textBoxId.Text;

How to implement a click event on textbox in ASP.NET?

In my web application I need a functionality so that when users click on textbox to input values, it should make the button and the other fields visible?
I am using the code provided below but, could not get it working.
C#:
protected void TextBox1_Click(object sender, EventArgs e)
{
ButtonSearch.Visible = true;
}
ASP.NET:
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" Visible="False" />
How to accomplish this?
Set AutoPostback="True". This way the event will be fired server-side, and the button will become visible.
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click" AutoPostBack="true"></asp:TextBox>
However, if you only want to toogle visility of a button, you really should considerate javascript. This will save a trip back to the server.
<asp:TextBox onclick="txtBox1_ClientClicked()" ID="TextBox1" runat="server" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" style="display:none;" />
<script type="text/javascript">
function txtBox1_ClientClicked(){
var theButton = document.getElementById('<%=ButtonSearch.ClientID%>');
theButton.style.display = 'block';
}
</script>
You do not need to post back to the server to accomplish your job. You can use client side onFocus event and javascript/jquery, for example.
I know I used an input of type text, and you are using an ASP Control which posts on server, but here is a JSFiddle to get you on the right track: http://jsfiddle.net/Mmjtz/1/
$("<%= ButtonSearch.ClientID %>").click(function(){
$("#TextBox1").show():
});
In this code you need to pass fields ID which you want to visible on the click of button.
Put the textbox inside a div and use the div's onClick event from codebehind. It's not what you asked but it works for me without any errors. Here is a javascript function to implement requested event:
function toggleVisibility()
{
document.getElementById('TextBox1').disabled = true;
/*
...some other code...
*/
}
And of course, you have to define your onclick event at the div definition after implementing this JS function.
<div id="TBdiv" onClick="toggleVisibility()">
<asp:TextBox ID="TextBox1"..../>
</div>
IMPORTANT: Since you now disabled your TextBox from codebehind, you have to enable it in somewhere before you want to use it again. Otherwise you will not see it while the page is running.
jQuery is the perfect solution for your problem. The code would be something like this:
$("#TextBox1").on("click",function(){$("#ButtonSearch").css("visibility", "visible");})
You include the script by adding <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> to the page and then you can add the piece of code above to within <script></script> tags.

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...

Categories