Default radio button not triggering an UpdateControl postback - asp.net

I have three radio buttons on a form - A, B, C. Each of these selections populates a dropdown list with data specific to the option. When the form loads, I set option A to be checked (as the default).
When I select buttons B or C, the AsyncPostBack triggers fine and the dropdown is populated. BUT, subsequently selecting A from either B or C does not trigger the event.
I suspect that because A was checked when the form loaded, the browser is not seeing any "change" to raise the event.
So what can be done to enable the default A button recognise it is being changed from B or C in order to raise the postback?
I have tried both setting the checked state of button A in code on inital loading of the page only (ie IsPostBack is False) and alternatively setting the checked attribute of the radiobutton in the html, with the same results. If I don't default the radio button the functionality works as expected, except I don't have the radio button and dropdown list defaulted when the page first loads.
The html...
<asp:RadioButton ID="radBook" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="Book" />
<asp:RadioButton ID="radCD" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="CD" />
<asp:RadioButton ID="radDVD" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="DVD" />
<asp:UpdatePanel ID="pnlTasks" runat="server" UpdateMode="Conditional" RenderMode="Inline">
<ContentTemplate>
<asp:DropDownList ID="dropShippingSize" runat="server" CssClass="dropdownMandatory"></asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="radBook" />
<asp:AsyncPostBackTrigger ControlID="radCD" />
<asp:AsyncPostBackTrigger ControlID="radDVD" />
</Triggers>
</asp:UpdatePanel>
The code behind...
Sub Page_Load
If Not Me.IsPostBack Then
radBook.Checked = True
End If
End Sub
Private Sub rad_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles radBook.CheckedChanged, radCD.CheckedChanged, radDVD.CheckedChanged
zLoadShippingSizeDropdown()
End Sub

I had the same problem and looked for an answer for hours. This seems to have nothing to do with ViewState or anything similar, but with some kind of incompatibility of using a pre-checked RadioButton as trigger for an Async PostBack.
The work around I found is amazingly easy and worked right away; instead of using the checked=true on the mark-up or myRadioButton.Checked on the server side, I did the following:
Not setting the attribute on Mark-up and add this on the Page_Load event:
if (!IsPostBack)
{
MyRadioButton.InputAttributes["checked"] = "true";
...
}
I hope this helps and saves some people hours of hair pulling :)

I'm guessing you need to need to check if the page is a postback in your load event:
protected void Form_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
// Set radiobutton A...
}
}

We had the same problem and it seems you will have to set the other "checked" property for radio buttons to "false".
So please add the lines
radCD.Checked = False
radDVD.Checked = False

Are you by chance handling viewstate in your code behind as well? If so then you need to handle the AJAX version of it as viewstate can often be lost on AJAX style pages. Try putting your buttons inside the update panel and see if you get the same behaviour if the panel has it's update mode set to conditional. Don't worry about the postback triggers if you do that.
The asynch triggers are only for items inside an update panel. any item outside of a panel will doa full postback by design.
<asp:UpdatePanel ID="pnlTasks" runat="server" UpdateMode="Conditional" RenderMode="Inline">
<ContentTemplate>
<asp:RadioButton ID="radBook" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="Book" />
<asp:RadioButton ID="radCD" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="CD" /><asp:RadioButton ID="radDVD" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="DVD" />
<asp:DropDownList ID="dropShippingSize" runat="server" CssClass="dropdownMandatory">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>

WOW, I would have never thought that could be the bug. Saved many hours of frustration.
Thanks Juan going through the carppy Microsoft issue and found a solution for the rest.

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.

Label is not printing any value in ASP.NET using VB

Need your expertise on the issue.
Background: I have a label control in the presentation layer which is purely used for status display. Status could be Update Fail Pass/Delete/Duplicate record etc. that is happening through GridView (refer Code 1).
The status in this label is shown using code behind procedure (refer Code 2)
Issue: The procedure is not displaying anything when called from UpdateTableRecordInDatabase(...) but it works when I hit the button (created test button to evaluate whether is there any issue in the code). I did the debug and the values are being passed successfully without any issues.
Code 1
<asp:Label ID="lblStatus" runat="server" visible="false"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="TablesUpdatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="ListOfTables" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
DataKeyNames="PK_RestaurantTableID"
DataSourceID="DataSource1" Width="100%" CssClass="dataTable"
PageSize="15" ShowFooter="True" CellPadding="5"
CellSpacing="5" ShowHeaderWhenEmpty="True"
EmptyDataText="No records available in database"
OnRowUpdating = "UpdateTableRecordInDatabase"
OnRowDeleting="ListOfTables_RowDeleting">
<SortedAscendingHeaderStyle CssClass="sortasc" />
<SortedDescendingHeaderStyle CssClass="sortdesc" />
<columns>.....</columns>
</asp:GridView>
<asp:SQLDataSource .....>....</asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ListOfTables" />
</Triggers>
</asp:UpdatePanel>
</div>
Code 2
Protected Sub UpdateTableRecordInDatabase(sender As Object, e As GridViewUpdateEventArgs)
If CheckForDuplicateRecords(intAccountID, strTableName) = FALSE then
code here to update the table
else
e.Cancel = TRUE
Response.Redirect(Request.Url.AbsoluteUri)
PrintExceptionStatus("Table Names should be unique")
end if
End Sub
Sub PrintExceptionStatus(strMessage As String)
lblStatus.Visible = True
lblStatus.BackColor = Drawing.Color.LightYellow
lblStatus.ForeColor = Drawing.Color.Red
lblStatus.Text = "<img src='Images/error.png' align='absmiddle' hspace='5'>" + strMessage.ToString()
End Sub
Is there anything which I am overlooking or missing. Please guide.
Note that the GridView that fires the event is inside the UpdatePanel. Here is how it works - when the postback is triggered by something inside the UpdatePanel, the whole page life cycle is run, but then only the part of the page inside the UpdatePanel is updated on the client page.
So, after the GridView triggers the event, the text of the label is changed in the code behind (as you can see in debug), but since it is not inside the UpdatePanel the label is not changed, as you can see.
To solve the issue simply move the label inside the UpdatePanel - this make it a part of the HTML that is updated when postback inside UpdatePanel occurs:
<asp:UpdatePanel ID="TablesUpdatePanel" runat="server">
<ContentTemplate>
<asp:Label ID="lblStatus" runat="server" visible="false"></asp:Label>
Note that since it is inside the template, you might need FindControl now to access the label.
If you execute the UpdateTableRecordInDatabase the debugger goes in the if block or else block? If it goes in the else block you have written:
Response.Redirect(Request.Url.AbsoluteUri)
and after that you have called
PrintExceptionStatus("Table Names should be unique")
so in this case Page will be redirected to the given URL and if you have given URL as that of the current page it will definitely make the label to visible false as again the page load event will occur so try commenting Response.Redirect(Request.Url.AbsoluteUri)

ASP.NET Ajax Text Box with Button not firing

Hey just wondering if my syntax is wrong here
<asp:UpdatePanel ID="UpdatePanel2"
runat="server"
UpdateMode="Always">
<ContentTemplate>
<asp:textbox id="searchProductName" runat="server"></asp:textBox> <asp:Button ID="btnProductSearch" runat="server" Text="Search Product Name" CssClass="search" OnClick="ProductSearch_Click" UseSubmitBehavior="true" CausesValidation="false" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnProductSearch" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
and my OnClick method
Protected Sub ProductSearch_Click(ByVal sender As Object, ByVal e As EventArgs)
' Filter by ProductName
If searchProductName.Text.Length > 0 Then
srcProductListPerCustomer.FilterExpression = " (productName like '%" + searchProductName.Text.ToString & "%')"
productListTable.DataBind()
Else
srcProductListPerCustomer.FilterExpression = ""
productListTable.DataBind()
End If
End Sub
The problem is nothing is happening when I click on the button. The button works fine without the Ajax
Your button doesn't need to be in an UpdatePanel. The controls in a UpdatePanel should be the controls that are to be updated asynchronously. Put your UpdatePanel around the GridView you're updating, and use the AsyncPostBackTrigger in the same way.
It's best to keep UdpatePanels as small as possible; the fewer controls inside them, the less HTML will be sent back from the server (less bandwidth, faster request/response time). PostBackTriggers can refer to controls outside of the UpdatePanel with no problems.

How to refresh an opened popup extender panel

I have a gridview where I have button for each row. After clicking this button, the Modal PopUp Extender Panel is opened (with PanelName.Show()). The Panel contains a user control, which shows some labels, textboxes,etc. with an additional info binded form SqlDataSource. Until this point it works well. But, when I click another button, the panel is purely shown but the content is not refreshed (based on which button is clicked, some details info should be shown). Basically, the method SqlDataSource_Selecting is called only for the panel popup showing but not anymore.
How can I force panel to be refreshed (reloaded) after each PanelName.Show()??
Thanks in advance.
If I'm understanding your question correctly, I think the problem is that you just need to re-Bind your data bound controls after the user clicks the button to change the Selected item. You can use [ControlName].DataBind() to do that. Does that make sense?
It depends on whether the control(s) you want to refresh are DataBound() or not.
In other words, can you force the control to reload by using a DataBind() method call to force the control to reload itself, with either the same or new data?
Most GUI controls have the DataBind() method, but it's useless if the control is not actually using data to work!
This is why in your case your panel is not "refreshed" with new data because using a DataBind() on the panel does nothing. Using a databind() on the entire GridView is a different story and should work. Maybe place an UPDATEPANEL around the whole lot? If you do you have to be careful your normal edits and other Commands on the rows will continue to work.
However, What you can do is place the modalpopupextender inside your TemplateField, and using a "trick", you can keep your server post backs and still fire the popup panel.
ie
<asp:UpdatePanel ID="upADDMAIN" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnADD" runat="server" Text="NEW LOGIN" BackColor="Blue" Font-Bold="True" ForeColor="#FFFFCC" OnClick="btnADD_Click" />
<asp:Button ID="btnDUM" runat="server" style="display:none" />
<div style="height:20px">
</div>
<ajaxToolkit:ModalPopupExtender ID="mpeADD" runat="server"
targetcontrolid="btnDUM"
popupcontrolid="upADD"
backgroundcssclass="modelbackground">
</ajaxToolkit:ModalPopupExtender>
<asp:UpdatePanel ID="upAdd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlADD" runat="server" Width="700px" HorizontalAlign="Center" CssClass="auto-style10" Height="200px">
..
..
<div id="puFTR" class="auto-style17" style="vertical-align: middle">
<asp:Button id="btnOK" runat="server" Text="OK" style="width: 80px" OnClick="btnOK_Click" />
<asp:Button id="btnCAN" runat="server" Text="CANCEL" style="width: 80px" OnClick="btnCAN_Click" CausesValidation="False" />
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</asp:UpdatePanel>
As you may see, the btnDUM control is a Dummy to get the MPE to work, but it's not actually used as it's hidden by the style="display:none" tag.
However, the btnADD does work because it calls a Click() method on the server side which does the refresh of data on your new row. You may have to use a little jScript to pass the ROWINDEX into the Click() method for it to work with a GridView.
Incidentally, the Click() method in my case "controls" the MPE manually...
protected void btnADD_Click(object sender, EventArgs e)
{
ClearADDform();
mpeADD.Show();
}
protected void ClearADDform()
{
txtLOGIN.Text = string.Empty;
cbISActive.Checked = true;
txtPWD.Text = string.Empty;
ddlAgent.SelectedIndex = -1;
}
In my case, the above code example is outside a GridView, so you'll need to adjust.
But the point is, you can still have Server Side calls using Ajax popups!
Good luck.

RadioButtonList inside UpdatePanel inside Repeater, Can I?

I have a repeater with a RadioButtonList inside the ItemTemplate, but when the RadioButtonList.OnSelectedIndexChanged event fires it generates a full postback. What have I done wrong in my code below? How can I get the OnSelectedIndexChanged to generate an Async Postback?
<asp:UpdatePanel runat="server" ID="UpdatePanel2">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="sqlOptions">
<ItemTemplate>
<asp:UpdatePanel runat="server" ID="pnlA">
<ContentTemplate>
<strong>
<%# Eval("Name") %></strong><br />
<asp:RadioButtonList ID="RadioButtonList1"
DataSourceID="sqlOptionValues" runat="server"
DataTextField="id" DataValueField="Id" AutoPostBack="true"
OnSelectedIndexChanged="LoadPrice"
ValidationGroup="options" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ForeColor="Red" runat="server"
ControlToValidate="RadioButtonList1"
ErrorMessage="Required Field"
ValidationGroup="options" />
<asp:SqlDataSource ID="sqlOptionValues" runat="server"
ConnectionString="<%$ ConnectionStrings:
ConnectionString6 %>"
SelectCommand='<%# "SELECT DISTINCT OptionValue.Name,
OptionValue.Id FROM CombinationDetail
INNER JOIN OptionValue
ON CombinationDetail.OptionValueId = OptionValue.Id
WHERE (OptionValue.OptionId =" +
Eval("Id") + ")" %>'>
</asp:SqlDataSource>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Many thanks for any help :)
This is a real-world use case. I have a page with Repeaters, Ajax Accordions inside of other Accordions, Update Panels inside other Update panels, you name it. The page works great, except when I want to update one of the Accordion panels with my RadioButtonList (RBL). Even with the RBL inside an update panel, it causes a postback of the entire page. I tried everything. I finally realized it wasn't me when I noticed my buttons would work just fine. I figure it must be a bug in either the framework or the Ajax Control Toolkit. I did find people reference this link all over the web (http://blog.smarx.com/posts/the-case-of-the-radiobuttonlist-half-trigger.aspx), but this link from 2007 is dead now and probably no longer applicable, so that's no help.
What I ended up doing was going with what works - that submit button. All I did was add an onclick attribute to the RBL to call a hidden button. Now you don't want to set the button to Visible=false because then the button won't appear in the generated markup. Instead, set the button's style to display:none; so that no one will see this hack, because yes, that's what this workaround is - it's a hack, but simple and just as effective as what you'd expect. Don't forget to remove the Autopostback="True" from your RBL.
CAVEAT: Because I'm using a hacked button for the onclick event, it's possible for the user to click in the area of the RBL, but not actually select an item. When this happens, our onclick triggers an AsyncPostBack and the codebehind logic will be processed, so please keep that in mind. To give you an idea of what I mean: all the Page_Load() events will be called, but rbl_Questions_SelectedIndexChanged() won't be if they happen to click in the area of the RBL without actually selecting an item. For my purposes this causes no issues in my logic and has no effect on the user.
Here's the Code:
Somewhere In the .Aspx Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="rbl_Questions" runat="server"
OnSelectedIndexChanged="rbl_Questions_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:Button ID="btn_rbl_Questions" runat="server" style="display:none;"/>
<asp:Label ID="lbl_Result" runat="server" Text="" Visible="false">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
In the Page_Load() event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//Instead of using the AutoPostback of the RBL, use this instead.
rbl_Questions.Attributes.Add("onclick",
"document.getElementById('"
+ btn_rbl_Questions.ClientID
+ "').click();");
//Bind your RBL to a DataSource, add items programmatically,
// or add them in the aspx markup.
}
}
In the rbl_Questions_SelectedIndexChanged() event:
protected void rbl_Questions_SelectedIndexChanged(object sender, EventArgs e)
{
//Your code here.
//My code unhid the lbl_Result control and set its text value.
}
Update 05/24/2011
The above "hack" is no longer necessary (I am leaving it above since this was marked as the answer by the author). I have found the best way to do this, thanks to this SO Answer:
Updatepanel gives full postback instead of asyncpostback
The code is much simpler now, just remove what I put in the Page_Load() method and remove the Button I used in the Aspx page and add ClientIDMode="AutoID" and AutoPostBack="True" to the control you want the UpdatePanel to capture.
Somewhere In the .Aspx Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="rbl_Questions" runat="server"
ClientIDMode="AutoID" AutoPostBack="true"
OnSelectedIndexChanged="rbl_Questions_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:Label ID="lbl_Result" runat="server" Text="" Visible="false">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
MS changed how ClientID's are generated in .net 4.0 from "AutoID" to "Predictable" and I guess the ScriptManager or UpdatePanel's weren't updated correctly to use it. I can't find documentation on why that is anywhere or if it was left that way by design.
I seriously don't miss winforms.
Try this:
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="pnlA">
You'll also need to setup
<Triggers>
//radio buttons
</Triggers>
Not sure how you'll do that since it's a dynamically built list.

Resources