no postback from asp:HiddenField in asp:UpdatePanel - asp.net

I have the following situation:
.ascx:
<script type="text/javascript">
$(document).ready(function () {
$('.onoffswitch-checkbox').change(function () {
if ($(this).is(":checked"))
$('#hf').val(1);
else
$('#hf').val(0);
});
});
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="hf"/>
</Triggers>
<ContentTemplate>
<input type="checkbox" class="onoffswitch-checkbox">
<asp:HiddenField ID="hf" runat="server" Value="0"/>
<asp:Label ID="label" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
.vb:
Protected Sub hf_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) Handles hf.ValueChanged
label.Text = "something..."
End Sub
JS function changes the value of HiddenField after the CheckBox is checked or unchecked, but the ValueChaneged-Event of the HiddenField doesn't fire. I tryed with asp:PostBackTrigger - also no effect, can you see the error?
EDIT:
i tried also to declare the method in the control:
.ascx:
<asp:HiddenField ID="hf" runat="server" Value="0" OnValueChanged="hf_ValueChanged"/>
.vb
Protected Sub hf_ValueChanged(ByVal sender As Object, ByVal e As EventArgs)
label.Text = "something"
End Sub
no effect.

UpdatePanel will not work when you have Response.Write("") on event method. to change value of elements in UpdatePanel, try to use something like this:
hf.Value="something";

dear you need to add the OnValueChanged attribute in Hidden Field and declare the method name, then it will fire click event.
<asp:HiddenField ID="hf" runat="server" Value="0" OnValueChanged="hf_ValueChanged"/>
void hf_ValueChanged(Object sender, EventArgs e)
{
// Display the value of the HiddenField control.
string _strHDFValue = hf.Value;
Response.Write("something...")
}
Good Luck.

So, after 2 days experimentation i found the following workaround. It is not very pretty, but it works like I want.
I am not sure, but i think the JS changes the value of the hidden field only on the client site and the server doesn't see the changes and so is the event not fired.
at first I called manually a postback from js:
function changeHFValue(element) {
if ($(element).is(":checked"))
$('#<%= hf.ClientID %>').val(1);
else
$('#<%= hf.ClientID %>').val(0);
__doPostBack('UpdatePanel1', ''); //postback
}
ascx:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" EnableViewState="true">
<ContentTemplate>
<asp:HiddenField ID="hf" runat="server"/>
<input type='checkbox' onchange='changeHFValue(this);' id='cb'/>
<asp:Label ID="label" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
now is the event fired because of postback, it goes in the method in .vb:
Protected Sub hf_ValueChanged(ByVal sender As Object, ByVal e As EventArgs) Handles hf.ValueChanged
If hf.Value Then
label.Text = "something"
Else
label.Text = "something else"
End If
End Sub
the new problem was that the checkbox was always unchecked after postback, when the UpdatePanel was reloaded. The solution is to look at the HiddenField:
$(document).ready(function () {
// bind your events here initially
bind();
});
var prm = Sys.WebForms.PageRequestManager.getInstance(); // Page request manager
prm.add_endRequest(function () {
// re-bind your events here after postback
bind();
});
function bind() {
if ($('#<%= hf.ClientID %>').val() == 1)
$('#cb').prop('checked', 'checked');
else
$('#cb').prop('checked', '');
}

if not works after, add this attribute to UpdatePanel tag:
ChildrenAsTriggers="true"

See your Page_Load if you have any Response.*, if then, you should avoid it when load caused by UpdatePanel.

Related

TextBox TextChange event is not working in vb.net

I am using asp textbox control with TextChange event, trying to set the text to label as the textbox text get changed but it is working when i loose the focus from textbox not when text changes.
the problem with loosing focus is that if i use AutoPostBack="true" it refresh the page which affects my other values...
my source for textbox on aspx page
<asp:TextBox ID="txtSearchCust" runat="server" Width = "200" OnTextChanged="txtSearchCust_TextChanged" AutoPostBack="true" />
my code behind page source
Protected Sub txtSearchCust_TextChanged(sender As Object, e As EventArgs) Handles txtSearchCust.TextChanged
QtyChk.Text=txtSearchCust.Text
End Sub
here QtyChk is the label where I am trying to set the text
any solution...?
Based on your question.
<script type="text/javascript">
function doTextBoxChange() {
__doPostBack();
}
</script>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" onkeydown="return doTextBoxChange();"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack() Then
LabelChange()
End If
End Sub
Sub LabelChange()
Label1.Text = "1234"
End Sub
But I think use javascript is a better option.
The values will disappear after post, you need to request the value and setup.
otherwise, use viewstate or session.
Using the javascript, don't post form data.
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" onkeyup="return doTextBoxChange();"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
function doTextBoxChange() {
var inputValue = document.getElementById("TextBox1").value;
document.getElementById('<%= Label1.ClientID %>').innerHTML = inputValue;
}

ASP.NET UpdatePanel - inline variable

I have a server-side variable which is assigned a value in PreRender. For the sake of simplicity, let's imagine I'm doing this:
protected string test;
protected void Page_PreRender(object sender, EventArgs e)
{
test = Guid.NewGuid().ToString();
}
In my markup, the variable is then referred to within an UpdatePanel, like so:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Perform postback" />
<script type="text/javascript">
Sys.Application.add_load(function () {
alert('<%=test%>');
});
</script>
</ContentTemplate>
</asp:UpdatePanel>
On first load of the page, the JavaScript alert function gives me a random value, as expected. However, on any subsequent postback, the original value of the Guid is retained.
Can anybody explain why this is so, and offer a solution? I'm fairly sure I can achieve the required behaviour by putting the value of 'test' in a hidden field, for example, but ideally I wouldn't have to sink to those depths. Unfortunately replacing the UpdatePanel with something lighter isn't really an option.
I've found a solution to this, and nor is it quite as dirty as I'd feared. I declare a JS variable outside of the function:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Perform postback" />
<script type="text/javascript">
var test;
Sys.Application.add_load(function () {
alert(test);
});
</script>
</ContentTemplate>
</asp:UpdatePanel>
In my code-behind, I assign the JS variable a value in the Sys.Application.add_init method, like so:
protected void Page_PreRender(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(UpdatePanelTest), "startupScripts", "Sys.Application.add_init(function() {test='" + Guid.NewGuid().ToString() + "';});", true);
}
Voilà, a different Guid is then displayed on first load and every postback.

textChanged event doesn´t fire and i have autopostback=true

I have a textbox event declarated but it doesn´t fire. I have seen in SO other answers but all of them say that autopostback property has been true and i have it
my aspx
<asp:ScriptManager ID="ScriptManager2" runat="server" />
<asp:TextBox runat="server" ID="txtDia" Width="120px" Height="20px"
AutoPostBack="True" CssClass="textbox" OnTextChanged="txtDia_TextChanged"/>
<Juice:Datepicker ID="Datepicker2" runat="server" TargetControlID="txtDia"
DateFormat="dd/mm/yy"
MonthNames="Enero,Febrero,Marzo,Abril,Mayo,Junio,Julio,Agosto,Septiembre,Octubre,Noviembre,Diciembre"
MonthNamesShort="Ene,Feb,Mar,Abr,May,Jun,Jul,Ago,Sep,Oct,Nov,Dic,"
AutoPostBack="True" /></td>
and my aspx.vb
Protected Sub txtDia_TextChanged(sender As Object, e As System.EventArgs) Handles txtDia.TextChanged
CargarDatos()
End Sub
You should define your textbox like this (see OnTextChanged="txtDia_TextChanged" being added):
<asp:TextBox OnTextChanged="txtDia_TextChanged"
runat="server" ID="txtDia" Width="120px" Height="20px"
AutoPostBack="True" CssClass="textbox"/>
And remember that this event will rise onblur (focus removed from that textbox) only.
In your aspx you should write
<asp:TextBox runat="server" ID="txtDia" Width="120px" Height="20px"
AutoPostBack="True" CssClass="textbox" OnTextChanged="txtDia_TextChanged"/>
The event is not triggered if you overwrite the text in codebehind. So for example if you databind the control where the TextBox sits in.
You should so that only If Not IsPostBack:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
DataBindAllControls(); // including your textbox
}
}
Edit: Sorry, here VB.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
DataBindAllControls() ' including your textbox
Else
End Sub
What FAngel said is correct.
I've had the same issue when validating dates and using jquery datepicker. I used the below to fire the validation routines after the box had been populated. So technically they fired twice, once after the textbox had lost focus to the datepicker, then again when my code fired after the datepicker had populated the textbox. It would have been better to disable the onblur event and call directly from the below, but wasn't possible in my project.
$('.datePicker').each(function () {
$(this).datepicker({
onSelect: function () {
$(this).trigger('blur');
}
});
});
You can use a variation on this by disabling the auto-postback and manually triggering it via the onSelect event.
You need to specify the method to be called when the event is fired like so:
<asp:TextBox runat="server" ID="txtDia" Width="120px" Height="20px" OnTextChanged="txtDia_TextChanged" AutoPostBack="True" CssClass="textbox"/>
Note:
OnTextChanged="txtDia_TextChanged"

asp.net updatepanel and firefox Page.IsValid causes exception

I have the following asp.net code:
<script type="text/javascript">
$(document).ready(function () {$(".button").click(function (event) {
alert("Button pressed!");
});
});
</script>
<asp:Button ID="button" runat="server" CssClass="button" />
<asp:UpdatePanel ID="testUpdatePanel" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="testTextBox" EventName="TextChanged" />
</Triggers>
<ContentTemplate>
<asp:TextBox ID="testTextBox" runat="server" AutoPostBack="true" CausesValidation="true" ValidationGroup="test" CssClass="Test" />
<asp:RegularExpressionValidator ID="testRegularExpressionValidator" runat="server" ControlToValidate="testTextBox" ErrorMessage="*2" ValidationExpression="(19|20)\d\d\-(0[1-9]|1[012])\-([012][0-9]|3[01])" ValidationGroup="test" />
<asp:Label ID="testLabel" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
And the following codebehind:
Private Sub testTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles testTextBox.TextChanged
If (Not Page.IsValid) Then
Return
End If
testLabel.Text = testTextBox.Text
End Sub
If i run this in FF(v15,v15.0.1) type 1987-05-03 in the textbox and then press enter, it triggers the button, after that i get a postback to testTextBox_TextChanged, and when it hits he line If (Not Page.IsValid) Then i get the following exception:
Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.
If i do the same in IE the button is never triggerd, and i get no exception!
So why does FF misbehave like this? i have not set a DefaultButton on any of my panels..
Add
Page.Validate("test")
before that line and it will be guaranteed validated in all scenarios. It could still be happening in IE, but the error is swallowed somehow...
Add the CausesValidation property to true to your TextBox
Or, call this.Validate before checking the IsValid property
The above will remove the exception, however the incompatibility with IE and FF will remain

How to update a control outside of an updatepanel?

I am going to show some text in a TextBox, which is located outside of an updatepanel, after checking a CheckBox but I cannot make it work. please help me out ?
Here is my code:
<asp:UpdatePanel runat="server" ID="uplMaster">
<ContentTemplate>
<asp:CheckBox ID="cbShowText" runat="server" Text="Show Some Text" AutoPostBack="true"
OnCheckedChanged="cbShowText_CheckedChanged" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:TextBox ID="txtBox" Text="Empty" runat="server" />
Code Behind:
protected void cbShowText_CheckedChanged(object sender, EventArgs e)
{
txtBox.Text = "Some Text";
}
Thanks in advance :D
P.S. As you might have guessed, I have resembled my problem and that is why I don't want to put the TextBox in the UpdatePanel
I put the TextBox in another UpdatePanel and then called the Update method:
Here is my new code:
<asp:UpdatePanel runat="server" ID="uplMaster" UpdateMode="Always">
<ContentTemplate>
<asp:CheckBox ID="cbShowText" runat="server" Text="Show Some Text" AutoPostBack="true"
OnCheckedChanged="cbShowText_CheckedChanged" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server" ID="uplDetail" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtBox" Text="Empty" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void cbShowText_CheckedChanged(object sender, EventArgs e)
{
txtBox.Text = "Some Text";
uplDetail.Update();
}
Hope this helps
The textbox has to be in update panel also.
*Edit:
I am sorry I didn't read your question properly. Perhaps write a javascript function, and call the function from codebehind?
I know its been a while since this was asked, but here is what I did. Like #bla said write a javascript function and call it from code behind.
So in your checked changed call this. The changeText is a javascript function on your page in the header or in a script file.
protected void cbShowText_CheckedChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "Show Different Text", "changeText();", true);
}
Sample Javascript. Just gets called when checked changed event fires from code behind.
<script type="text/javascript">
function changeText() {
var txt= document.getElementById('<%= txtBox.ClientID %>');
var chk = document.getElementById('<%= cbShowText.ClientID %>');
if (chk.checked === true) {
txt.Text = "Something";
} else {
txt.Text = "Somethingelse";
}
}
</script>
Hope this helps someone.

Resources