ASP.NET Label Inside UpdatePanel Not Updating - asp.net

I am new to ASP.NET and I'm trying to get a Label to update with some information that is grabbed when I hit a button. The click function is called and returns just fine (I've debugged and stepped through the whole thing). The only thing that doesn't work is where I set the text of the Labels I'm trying to update.
This is the function that gets called on the button click:
Protected Sub submitbutton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitbutton.Click
Dim res As String() = query(email1.Text)
If Not res Is Nothing Then
url1.Text = res(0)
date1.Text = res(1)
End If
End Sub
I know it goes into the if and tries to set the text but nothing happens on the client side.
This is the UpdatePanel I have:
<asp:UpdatePanel ID="UpdatePanelSettings" runat="server" UpdateMode="Always" >
<Triggers>
<asp:AsyncPostBackTrigger ControlID="submitbutton" EventName="click" />
</Triggers>
<ContentTemplate>
<table>
<tr>
<td>Emails</td><td>Url Parsed</td><td>Date Created</td>
</tr>
<tr>
<td>
<asp:TextBox runat="server" ID="email1" Width="300" />
</td>
<td>
<asp:Label runat="server" ID="url1" Text="-" />
</td>
<td>
<asp:Label runat="server" ID="date1" Text="-" />
</td>
</tr>
<tr>
<td colspan="3"><asp:Button ID="submitbutton" runat="server" Text="Submit" /></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
As I said, I know the trigger works because I've stepped through the code when it is called. I know that you also need a ScriptManager, which I have right inside the form element that comes in the Site.Master file (I really just stuck stuff in the default template. It's just a proof of concept project).
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
From all the articles I've found on the web, this should be all I need. One article mentioned having to do things with the Web.Config, but it said that for VS 2005 and I'm using 2010. It mentioned you didn't have to change anything in 2008, so I figured the same was true for 2010. What am I missing that I need to get the labels to update?

I haven't worked with this for a while, but you may need to explicitly call:
UpdatePanelSettings.Update()
At the end of your command.
.
Give it a try anyway.

Can you try removing the section.
<Triggers>
<asp:AsyncPostBackTrigger ControlID="submitbutton" EventName="click" />
</Triggers>
Then change the UpdatePanel by add ChildrenAsTriggers="true" to it.
<asp:UpdatePanel ID="UpdatePanelSettings" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" >
In theory, this should be exactly the same as the way you have it above, but just trying to help you debug it.

1) Is it possible res is two blank items?
2) Is there any other code that touches the two labels (like when the form loads)?

Related

update panel webcontrol required form field

I created a simple control which uses an update panel with a button click trigger and yes a script manager above the control. Click the button and a label is updated with the current time and this has worked fine for 6 years
Today, I changed the page to be responsive with Bootstrap but this is irrelevant to this question.
The control was added to a page which has labels and textboxes (simple form with first name / last name).
<asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control input-lg" Placeholder="Your First Name" MaxLength="20" Required="true"></asp:TextBox>
If I remove:
Required="true"
and click the button in the control the date / time updates but placing this back stops the date / time updating. I need to use both as I wish for the first name to be required but also for the time to update
Simple Example:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" Text=""></asp:Label>
<asp:Button ID="btnRefreshTime" runat="server" Text="Refresh Time" OnClick="btnRefreshTime_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnRefreshTime" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code Behind:
Protected Sub btnRefreshTime_Click(sender As Object, e As EventArgs)
lblTime.Text = DateTime.Now.ToString()
End Sub
What am I doing wrong and what would I need to do to resolve it without opening the form up to abuse (script attacks) etc? I don't wish to add the following to the page directive:
ValidateRequest="false"
Thank you in advance
Probabily the button server side event is prevented to execute due to the client side validation of required = "true".
Try to change the button with somewhat else which does not trigger client side validation by design. I would try with a LinkButton.

Issue in displaying loader gif via Ajax

I have a below section which is implemented to display loader gif associated to the update panel
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="updPnlPromotion">
<ProgressTemplate>
<img alt="" src="Image/Ajaxloader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
This is the update panel which contains the dropdown which is a data bound control binded on the radio button checked changed event, but rather than partial postback and the display of loader gif, the entire page posts back.
<asp:UpdatePanel ID="updPnlPromotion" runat="server" UpdateMode="Always">
<ContentTemplate>
<td align="left" style="width: 20%;background-color:#CDCD9C">
<asp:radiobutton ID="rdbPromotion" runat="server" Text="New Promotion" AutoPostBack="true" GroupName="TacPlan" OnCheckedChanged="rdbPromotion_OnCheckedChanged" style="font-weight:bold" />
</td>
<td align="left" style="width:30%; vertical-align:middle; background-color:#EBEBEB; text-align:center">
<asp:DropDownList runat="server" ID="ddlPromotion" Width="95%"></asp:DropDownList>
</td>
<td>
<asp:Label Text="*" ForeColor="Red" Visible="false" runat="server" ID="lblPromoPlanMandatory"></asp:Label>
</td>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rdbPromotion" EventName="CheckedChanged" />
</Triggers>
</asp:UpdatePanel>
I don't believe there's an issue with the code you've posted. I created a new ASPX page and copied your code into it. It works as expected (I added a counter to monitor load events):
Here's the code behind I used for testing this:
Public Sub rdbPromotion_OnCheckedChanged(sender As Object, e As EventArgs) Handles rdbPromotion.CheckedChanged
System.Threading.Thread.Sleep(2000)
End Sub
Private Sub Default5_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.counter.Text = Integer.Parse(Me.counter.Text) + 1
End Sub
Seems like a longshot, but maybe the browser you're testing with doesn't support partial rendering, or ASP.NET doesn't think that it does?:
http://ajax.asp.net/ajax/documentation/live/mref/P_System_Web_UI_ScriptManager_EnablePartialRendering.aspx
I have found the solution to my problem, upon reviewing the web.config file I found the weird setting xhtmlConformance mode="Legacy" there which was basically stopping the page to ajaxify somehow, by removing it, it works as expected.

Using TextBox TextChanged event to enable or disable a button control in asp.net

I am using an asp TextBox control with its TextChanged event and my goal is to capture text as a user enters it. If there are one or more characters entered, I would like a button control to be enabled without the user having to leave the TextBox control.
My source code for the TextBox on the aspx page is
<asp:TextBox ID="NewSpendingCategoryTextBox" MaxLength="12" runat="server"
AutoPostBack="True"
OnTextChanged="NewSpendingCategoryTextBox_TextChanged"
ViewStateMode="Enabled" >
</asp:TextBox>
and my source code on the code behind page is
Protected Sub NewSpendingCategoryTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles NewSpendingCategoryTextBox.TextChanged
Dim strSpendingCategoryTextBox As String = Nothing
strSpendingCategoryTextBox = NewSpendingCategoryTextBox.Text
If strSpendingCategoryTextBox.Length <= 0 Then
Me.NewSpendingCategoryInsertButton.Enabled = False
Else 'strSpendingCategoryTextBox.Length > 0
Me.NewSpendingCategoryInsertButton.Enabled = True
End If 'strSpendingCategoryTextBox.Length <= 0
End Sub
So it appears I have to use javascript to enable or disable the insert button. Can someone guide me on how to get an element within a table? The table sits in a Panel as well.
below is the aspx code...
<asp:Panel ID="AddSpendingCategoryPanel" Visible="false" runat="server">
<table class="AddNewTable">
<tbody>
<tr>
<td>
<asp:Label ID="lblSpend" runat="server"
Text="Spending Category:">
</asp:Label>
</td>
<td>
<asp:TextBox ID="txtSpend" MaxLength="12"
runat="server"
AutoPostBack="True"
OnTextChanged="txtSpend_TextChanged"
OnKeyDown="return CheckSpendTextBoxValue()"
ViewStateMode="Enabled" >
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button CssClass="frmbtn" ID="btnInsertSpend"
runat="server" Text="Insert" />
</td>
<td>
<asp:Button CssClass="frmbtn" ID="btnCancelSpend"
runat="server" Text="Cancel"
CausesValidation="False" />
</td>
</tr>
</tbody>
</table>
</asp:Panel>
Run this code in the OnKeyPress event or consider JavaScript. The textbox does not fire the Text_Changed event til Tab or Enter are used.
Simplify the boolean check.
Me.NewSpendingCategoryInsertButton.Enabled = (NewSpendingCategoryTextBox.Text.Length <> 0)
I'm not sure exactly how you would do it. But the ASP.NET code is executed on the server that is hosting the web page.
I'd highly recommended doing it on JavaScript which can be run client side. Hopefully this article is of use to you.
How to check if a textbox is empty using javascript

DropDownList in ModalPopup/UpdatePanel intermittently does not fire SelectedIndexChanged

I've got a UserControl that's used inside of an UpdatePanel.
The UserControl is a fairly simple form that appears via a ModalPopupExtender (which is also part of the UserControl). There are four DropDownLists, as well as some other UI elements.
Three of the four DropDownLists have AutoPostBack="true", with SelectedIndexChanged events that fire on the server and cause some of the other DropDownLists to rebind.
Two of the three DDL's that AutoPostBack are working fine. One of them, which I only just added, is showing some strange behavior.
Let's say I bind five Items to it: 1, 2, 3, 4, 5. I set the SelectedIndex to 0, which makes 1 the selected item.
If I select 5 and then 1 and keep toggling back and forth, everything works fine. The postback occurs and SelectedIndexChanged fires. Every time.
If I ever select 2 or 4, the postback occurs but SelectedIndexChanged does not fire. Every time.
If I ever select 3, something bizarre happens and sometimes the value of the DDL reverts to 1. Even though breakpoints seem to show that it's not rebinding and no unexpected code is running. I know your first instinct will probably be that I'm wrong about the rebinding code not running, but I have literally been staring at the debugger for hours trying to find my mistake. Lots of breakpoints. I don't get it -- this really isn't that complicated.
But obviously I am missing something.
I've put about four hours into this so far and I think I'm just grinding at this point. I could use another perspective.
HTML (and by the way, DropProtocolCycleID is the problem control):
<asp:Panel ID="PanelPopupAssign" runat="server" Style="display:none; cursor: move; width:325px; background-color:Transparent;">
<BlueUI:Panel runat="server" ID="PanelPatientProtocol" Width="500px" HeaderText="Assign Protocol">
<table cellspacing="5">
<tr>
<td style="width:150px;"></td>
<td style="width:50px;"></td>
<td style="width:125px;"></td>
</tr>
<tr runat="server" id="TableRowCategory">
<td align="right">Category:</td>
<td colspan="2">
<asp:DropDownList runat="server" ID="DropProtocolCategories" CausesValidation="false" autopostback="true"/>
</td>
</tr>
<tr>
<td align="right">Protocol:</td>
<td colspan="2">
<asp:DropDownList ID="DropProtocolID" runat="server" Enabled="false" CausesValidation="false" autopostback="true"/>
<asp:Label ID="LabelProtocolName_SetDate" runat="server" />
</td>
</tr>
<tr>
<td colspan="3">
<table style="margin-left: 120px">
<tr>
<td align="right">Cycle:</td>
<td><asp:DropDownList ID="DropProtocolCycleID" runat="server" autopostback="true" /></td>
</tr>
<tr>
<td align="right">Day:</td>
<td>
<asp:DropDownList ID="DropProtocolCycleDayID" runat="server" Enabled="false" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="right">Start Date:</td>
<td colspan="2">
<table>
<tr>
<td>
<asp:Textbox ID="TextProtocolStartDate" runat="server" Width="65px"
BackColor="Transparent" BorderStyle="None" ReadOnly="True" Font-Size="11px"
ForeColor="#1C4071" Font-Names="Verdana" ValidationGroup="AssignProtocol" />
</td>
<td>
<img id="ImageProtocolStartDate"
alt="Calendar"
onclick="CalProtocolStartDate.show();"
class="calendar_button"
src="../../Images/Icons/btn_calendar.gif"
width="25"
height="22" />
<asp:RequiredFieldValidator ID="ValRequiredProtocolStartDate" runat="server" display="Dynamic"
ControlToValidate="TextProtocolStartDate" ErrorMessage="Protocol Start Date is required!"
InitialValue="(None)"
Enabled="false" ValidationGroup="AssignProtocol">*</asp:RequiredFieldValidator>
</td>
</tr>
</table>
</td>
</tr>
</table>
<ComponentArt:Calendar runat="server"
id="CalProtocolStartDate"
AllowMonthSelection="false"
AllowMultipleSelection="false"
AllowWeekSelection="false"
CalendarCssClass="calendar"
TitleCssClass="title"
ControlType="Calendar"
DayCssClass="day"
DayHeaderCssClass="dayheader"
DayHoverCssClass="dayhover"
DayNameFormat="FirstTwoLetters"
ImagesBaseUrl="~/Images/Calendar/"
MonthCssClass="month"
NextImageUrl="cal_nextMonth.gif"
NextPrevCssClass="nextprev"
OtherMonthDayCssClass="othermonthday"
PopUp="Custom"
PopUpExpandControlId="ImageProtocolStartDate"
PrevImageUrl="cal_prevMonth.gif"
SelectedDate=""
VisibleDate=""
SelectedDayCssClass="selectedday"
SelectMonthCssClass="selector"
SelectMonthText="¤"
SelectWeekCssClass="selector"
SelectWeekText="»"
SwapDuration="300"
SwapSlide="Linear"
AutoPostBackOnSelectionChanged="False"
PopUpCollapseDuration="0"
ClientSideOnSelectionChanged="onCalProtocolStartDateChange">
<ClientEvents>
<Load EventHandler="Calendar1_onLoad" />
</ClientEvents>
</ComponentArt:Calendar>
<br />
<div style="text-align:center;">
<asp:Button ID="ButtonSaveProtocol" runat="server" Text="Save" ValidationGroup="AssignProtocol" Enabled="false" />
<asp:Button ID="ButtonCancel" runat="server" Text="Cancel" CausesValidation="false" />
</div>
<br />
</BlueUI:Panel>
</asp:Panel>
<ajaxToolkit:ModalPopupExtender id="ModalPopupExtenderAssignProtocol" runat="server"
popupcontrolid="PanelPopupAssign" popupdraghandlecontrolid="PanelPopupAssign" CancelControlID="ButtonCancel"
targetcontrolid="ButtonAssignProtocol" BackgroundCssClass="modalBackground" RepositionMode="RepositionOnWindowResizeAndScroll" >
</ajaxToolkit:ModalPopupExtender>
Relevant codebehind:
Private Sub DropProtocolCycleID_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropProtocolCycleID.SelectedIndexChanged
Me.Show()
Me.SetupDropProtocolCycleDayID()
End Sub
Public Sub Show()
Me.ModalPopupExtenderAssignProtocol.Show()
End Sub
Here's the code where I bind DropProtocolCycleID, if you're interested. It fires in the SelectedIndexChanged event of DropProtocolID, which actually works reliably:
Private Sub SetupDropProtocolCycleID()
If Me.DropProtocolID.SelectedValue = Constants.NothingSelected Then
Me.DropProtocolCycleID.Enabled = False
Exit Sub
Else
Me.DropProtocolCycleID.Enabled = True
End If
Dim ProtocolID As Integer = Me.DropProtocolID.SelectedValue
Dim ProtocolCycles As DataTable = ProtocolManager.GenerateCycleTable(ProtocolID)
Me.DropProtocolCycleID.DataSource = ProtocolCycles
Me.DropProtocolCycleID.DataTextField = "ProtocolCycleNumber"
Me.DropProtocolCycleID.DataValueField = "ProtocolCycleID"
Me.DropProtocolCycleID.DataBind()
If DropProtocolCycleID.Items.Count > 0 Then
Me.DropProtocolCycleID.SelectedIndex = 0
End If
End Sub
ProtocolCycleNumber and ProtocolCycleID are just integers. No chance of anything in there that could interfere with the javascript.
This solution is ugly, but it works, and at this point I need to just get it working and move on.
In a nutshell, I added an invisible button and then made the DropDownList's onchange event click the button with JavaScript whenever it gets changed. This gets around whatever problem we're dealing with here.
I added this JS to the page:
function IndexChanged() {
document.getElementById("ctl00$MainContent$AssignProtocolControl$ButtonIndexChanged").click();
}
I changed the DropDownList to call that:
<asp:DropDownList ID="DropProtocolCycleID" runat="server" onchange="IndexChanged();" />
I added the invisible button:
<asp:Button id="ButtonIndexChanged" Text="Index Changed" style="display: none;" OnClick="DropProtocolCycleID_SelectedIndexChanged" runat="server" />
...And that solved the problem. Please let me know if you discover a better solution.
Oh, and as for the issue with the value sometimes being reverted to 1, it was because I needed to have duplicate values in my ListIems -- the text varied, but the values were sometimes the same.
Apparently when you do that, ViewState botches the job of restoring state and selects the first matched value it finds. So I just made my value a little more elaborate and it works fine now.
I had the same problem, I solved it by adding modalpop.show()
e.g.
AutoPostback=true in the design file
protected void ddlCars_SelectedIndexChanged(object sender, EventArgs e)
{
//Do all your work here
mpEditCars.Show();
}

Ajax callback UpdatePanel.Update() still reloading whole page

I have code in an Update Panel and even though on a button click i am inserting data into a db and simply calling Updatepanel.Update() the whole page is reloaded:
Gifts.ASPX
<table style="width:100%;">
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="Gift"></asp:Label>
</td>
<td>
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtNewGift" runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
Gifts.aspx.CS
protected void cmdAddGift_Click(object sender, EventArgs e)
{
OleDbConnection objConn = new OleDbConnection(DataSource);
Random r = new Random();
int giftID = r.Next(1200, 14000);
OleDbCommand objCommand = new OleDbCommand("Insert into Gifts (GiftID, Description) values (" + giftID + ",'" + txtNewGift.Text + "')", objConn);
ExecuteCommand(objCommand);
PopulateGifts(objConn);
txtNewGift.Text = "";
UpdatePanel3.Update();
}
Any ideas why this whole page would reload instead of just the textbox getting update?
Where is the button in the above example? Inside or outside the UpdatePanel. If it is outside you will need to add it to the triggers collection of the UpdatePanel.
Also you only need to call UpdatePanel.Update() if you are changing the content of an UpdatePanel other than the one that caused the (Partial) postback.
As a side note (and personal crusade), it is recommended that a using statement is put around your DB connection.
With the markup below, the following will happen:
btnInnerPart is inside the update panel, so it will automatically cause a partial postback
btnInnerFull will cause a full postback as it has a PostBackTrigger in the trigger collection
btnOuterPart will cause a partial postback as it has an AsyncPostBackTrigger in the trigger collection
btnOuterFull will cause a full postback as it is outside the UpdatePanel
Markup:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<!-- Content -->
<asp:Button runat="server" ID="btnInnerPart" Text="Inner Part" />
<asp:Button runat="server" ID="btnInnerFull" Text="Inner Full" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnOuterPart" />
<asp:PostBackTrigger ControlID="btnInnerFull" />
</Triggers>
</asp:UpdatePanel>
<asp:Button runat="server" ID="btnOuterFull" Text="Outer Full" />
<asp:Button runat="server" ID="btnOuterPart" Text="Outer Part" />
Where is the button on Gifts.ASPX? If you put the button inside the UpdatePanel or use triggers you don't need to call UpdatePanel3.Update(); from the code behind.
Also, You need to have a ScriptManager object on your page. Do you have one?
please check tag of update panel...you have to specify the trigger controls for update panel on on which the update panel will get update

Resources