How to prevent ajax toolkit DropDownExtender from closing on click? - asp.net

I have the code below to implement a dropdownlist with checkboxes. My problem is that every time i click a checkbox the dropdownlist closes and i need to reopen it to select more checkboxes. How do i make it so the dropdownlist dosn't close until i click off of it?
<asp:Panel ID="pnl_Items" runat="server" BorderColor="Aqua" BorderWidth="1">
<asp:CheckBoxList ID="cbl_Items" runat="server">
<asp:ListItem Text="Item 1" />
<asp:ListItem Text="Item 2" />
<asp:ListItem Text="Item 3" />
</asp:CheckBoxList>
</asp:Panel>
<br />
<asp:TextBox ID="tb_Items" runat="server"></asp:TextBox>
<ajax:DropDownExtender ID="TextBox1_DropDownExtender"
runat="server"
DynamicServicePath=""
Enabled="True"
DropDownControlID="pnl_Items" on
TargetControlID="tb_Items">
</ajax:DropDownExtender>

i prefer not altering AjaxControlToolkit. As follows:
$(document).ready(function() {
$('input[type=checkbox], label').click(function(e){
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation)e.stopPropagation();
});
});
change jquery selector to your checkboxes!

I was able to get the desired behavior by adding the following javascript that I found on this post.
var DDE;
function pageLoad()
{
DDE = $find('<%= TextBox1_DropDownExtender.ClientID %>');
DDE._dropWrapperHoverBehavior_onhover();
$get('<%= pnl_Items.ClientID %>').style.width = $get('<%= tb_Items.ClientID %>').clientWidth;
if (DDE._dropDownControl) {
$common.removeHandlers(DDE._dropDownControl, DDE._dropDownControl$delegates);
}
DDE._dropDownControl$delegates = {
click: Function.createDelegate(DDE, ShowMe),
contextmenu: Function.createDelegate(DDE, DDE._dropDownControl_oncontextmenu)
}
$addHandlers(DDE._dropDownControl, DDE._dropDownControl$delegates);
}
function ShowMe() {
DDE._wasClicked = true;
}

You will need to get the Ajax control toolkit source code and modify the DropDownExtender to behave the way you want it to. Each control has its own folder with all the files related to it's ability to function within.
Recompile, drop the new dll into your project.

Related

RegisterStartupScript from code behind not working when Update Panel is used

I have created a radiobutton list followed by one button. I can select one of the item from the radiobutton list and then click the button to execute something. And I want the page to pop up a window if the button is clicked without selecting any of the options from the radiobutton list. My codebehide is like this:
protected void ButtonPP_Click(object sender, EventArgs e)
{
if (radioBtnPP.SelectedIndex < 0)
{
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> alert('Please Select Criteria!') </");
cstext1.Append("script>");
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
}
}
}
and my html part is:
<asp:RadioButtonList class ="radioBtn" ID="radioBtnACO" runat="server">
<asp:ListItem Text="All Dim" />
<asp:ListItem Text="Select Dim" />
</asp:RadioButtonList>
<asp:Button id ="ButtonPP" class ="buttonRight" runat="server" Text="Run PP" OnClick="ButtonPP_Click" />
This works fine. However, now I don't want to refresh the whole page when i click the button, so I use updatepanel. And I changed my html code to the following:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="ControlUpdatePanel" runat="server" Visible="True">
<ContentTemplate>
<asp:RadioButtonList class ="radioBtn" ID="radioBtnACO" runat="server">
<asp:ListItem Text="All Dim" />
<asp:ListItem Text="Select Dim" />
</asp:RadioButtonList>
<asp:Button id ="ButtonPP" class ="buttonRight" runat="server" Text="Run PP" OnClick="ButtonPP_Click" />
</ContentTemplate>
</asp:UpdatePanel>
But now my code doesn't work anymore... If I don't select any option from the radiobutton list and just click the button, no window would pop up :( I am sure my codebehind is still executed but seems like it just doesn't passed to my .aspx page...
Anyone please help me out? I don't know what to do now... Millions of thanks!
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e)
{
if (radioBtnACO.SelectedIndex < 0)
{
string csname1 = "PopupScript";
var cstext1 = new StringBuilder();
cstext1.Append("alert('Please Select Criteria!')");
ScriptManager.RegisterStartupScript(this, GetType(), csname1,
cstext1.ToString(), true);
}
}

ASP.NET - Control dropdownlist postback programmatically

I have two dropdownlists on my form-ddl1 and ddl2. They together determine the visibility of a textbox -txt1. For that I do this check:
if (ddl1.SelectedIndex==2 && ddl2.SelectedIndex>2)
{
if (!txt1.Visible)
{txt1.Visible=true;// And then I want to call postback}
}
else
{
if (txt1.Visible)
{txt1.Visible=false;// And then I want to call postback}
}
As you can see, I want to post the page to server only if the above condions are true. The code above is triggered on SelectedIndexChanged event of the both dropdownlists. How can I or is it possible to achieve upon a condition?
I am not sure if i understand your problem but you want to achieve postback only if certain condition is met. you can hook up a javascript function on both dropdown onchange="return onchange();" Set Autopostback = true;
function Onchange() {
var ddl1 = document.getElementById('<%= ddl1.ClientID %>');
var ddl2 = document.getElementById('<%= ddl2.ClientID %>');
var txtbox = document.getElementById('<%= txtbox.ClientID %>');
if (ddl1.selectedIndex == 2 && ddl2.selectedIndex > 2) {
txtbox.style.display = "inline";
__doPostBack(ddl1, '');
}
else {
txtbox.style.display = "none";
return false;
}
}
Aspx code should look like this.
<asp:DropDownList runat="server" AutoPostBack="true" ID="ddl1" onchange="return Onchange();"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
<asp:ListItem Text="text4" />
</asp:DropDownList>
<asp:DropDownList runat="server" AutoPostBack="true" ID="ddl2" onchange="return Onchange();"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
<asp:ListItem Text="text4" />
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtbox" />
Tested it and it works...
If AutoPostBack = True, which it would have to be for your events to be firing just call a funciton when your condition is met. ASP.NET is always posting back, you just need to handle the condition, otherwise you have to handle the validation with JavaScript and manually post the page:
if (ddl1.SelectedIndex==2 && ddl2.SelectedIndex>2)
{
if (!txt1.Visible)
{
txt1.Visible=true;// And then I want to call postback
//dowork
}
}
else
{
if (txt1.Visible)
{
txt1.Visible=false;// And then I want to call postback
//do work
}
}

JQuery BlockUI with UpdatePanel Viewstate Issue

I have an update panel within a div that I modal using the JQuery plugin BlockUI. Inside the UpdatePanel is a textbox and a button. When I enter something in the textbox and click the button I am unable to retrieve the text in the textbox. When I debug it shows the textbox having no value.
<asp:UpdatePanel ID="upTest" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<div id="divTest">
<asp:TextBox ID="txtTestVS" runat="server" /><br />
<asp:Button ID="cmdTest" Text="TEST" OnClick="cmdTest_Click" UseSubmitBehavior="false" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
SERVER-SIDE:
protected void cmdTest_Click(object sender, EventArgs e)
{
string x = txtTestVS.Text;
}
This should clarify things. Here are the total contents of the page.
SHOW MODAL
<div id="divTest">
<asp:UpdatePanel ID="upTest" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtTestVS" runat="server" /><br />
<asp:Button ID="cmdTest" Text="TEST" OnClick="cmdTest_Click" UseSubmitBehavior="false" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
This is a common problem with dialog plug-ins. The problem is when content is put in the blockUI container, it's appended to the element, and no longer in the form being submitted to the server. To solve this you need to edit the blockUI code a bit:
Here's the source: http://github.com/malsup/blockui/blob/master/jquery.blockUI.js
Change this:
Line 262:
var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
to:
var layers = [lyr1,lyr2,lyr3], $par = full ? $('form') : $(el);
and this:
Line 382:
els = $('body').children().filter('.blockUI').add('body > .blockUI');
to:
els = $('form').children().filter('.blockUI').add('form > .blockUI');
That should get you going and the textbox values coming through.
(Response courtesy of Nick Craver https://stackoverflow.com/users/13249/nick-craver)
If you are trying to use blockUI on a button within an update panel (i.e. you click the button within the update panel and the UI gets blocked), you need to handle it using PageRequestManager events
prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(function() {
$.blockUI({ message: '<img src="../../Content/images/Busy2.gif" />' });
});
prm.add_endRequest(function() {
$.unblockUI();
});
Or on a button click, if you want to display a modal window with this text box and a button, you can try something like this

How to validate a user chose at least one checkbox in a CheckBoxList?

I've got a CheckBoxList control that I want to require the user to check at least ONE box, it does not matter if they check every single one, or 3, or even just one.
In the spirit of asp.net's validation controls, what can I use to enforce this? I'm also using the Ajax validation extender, so it would be nice if it could look like other controls, and not some cheesy server validate method in the codebehind.
<asp:CheckBoxList RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" ID="ckBoxListReasons" runat="server">
<asp:ListItem Text="Preliminary Construction" Value="prelim_construction" />
<asp:ListItem Text="Final Construction" Value="final_construction" />
<asp:ListItem Text="Construction Alteration" Value="construction_alteration" />
<asp:ListItem Text="Remodel" Value="remodel" />
<asp:ListItem Text="Color" Value="color" />
<asp:ListItem Text="Brick" Value="brick" />
<asp:ListItem Text="Exterior Lighting" Value="exterior_lighting" />
<asp:ListItem Text="Deck/Patio/Flatwork" Value="deck_patio_flatwork" />
<asp:ListItem Text="Fence/Screening" Value="fence_screening" />
<asp:ListItem Text="Landscape - Front" Value="landscape_front" />
<asp:ListItem Text="Landscape - Side/Rear" Value="landscape_side_rear" />
<asp:ListItem Text="Other" Value="other" />
</asp:CheckBoxList>
It's easy to do this validation server side, but I am assuming you want to do it client side?
JQuery can do this very easily as long as you have something that all checkbox controls have in common to use as a selector such as class (CssClass on your .NET control). You can make a simple JQuery function and connect it to a ASP.NET custom validator. Remember if you do go the custom validator route to make sure you check it server side as well in case javascript is not working, you don't get a free server side check like the other .NET validators.
For more information on custom validators check out the following links: www.asp.net and
MSDN
You don't need to use JQuery, it just makes the javascript function to iterate and look at all your checkbox controls much easier but you can just use vanilla javascript if you like.
Here is an example I found at: Link to original
<asp:CheckBoxList ID="chkModuleList"runat="server" >
</asp:CheckBoxList>
<asp:CustomValidator runat="server" ID="cvmodulelist"
ClientValidationFunction="ValidateModuleList"
ErrorMessage="Please Select Atleast one Module" ></asp:CustomValidator>
// javascript to add to your aspx page
function ValidateModuleList(source, args)
{
var chkListModules= document.getElementById ('<%= chkModuleList.ClientID %>');
var chkListinputs = chkListModules.getElementsByTagName("input");
for (var i=0;i<chkListinputs .length;i++)
{
if (chkListinputs [i].checked)
{
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
Side Note: JQuery is just a little js file include you need to add to your page. Once you have it included you can use all the JQuery you like. Nothing to install and it will be full supported in the next version of Visual Studio I think.
Here's a cleaner jQuery implementation that allows one ClientValidationFunction for any number of CheckBoxList controls on a page:
function ValidateCheckBoxList(sender, args) {
args.IsValid = false;
$("#" + sender.id).parent().find("table[id$="+sender.ControlId+"]").find(":checkbox").each(function () {
if ($(this).attr("checked")) {
args.IsValid = true;
return;
}
});
}
Here's the markup:
<asp:CheckBoxList runat="server"
Id="cblOptions"
DataTextField="Text"
DataValueField="Id" />
<xx:CustomValidator Display="Dynamic"
runat="server"
ID="cblOptionsValidator"
ControlId="cblOptions"
ClientValidationFunction="ValidateCheckBoxList"
ErrorMessage="One selection required." />
And finally, the custom validator that allows the client function to retrieve the target control by ID:
public class CustomValidator : System.Web.UI.WebControls.CustomValidator
{
public string ControlId { get; set; }
protected override void OnLoad(EventArgs e)
{
if (Enabled)
Page.ClientScript.RegisterExpandoAttribute(ClientID, "ControlId", ControlId);
base.OnLoad(e);
}
}
You can use a CustomValidator for that with a little bit of javascript.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one"
ClientValidationFunction="checkCheckBoxList"></asp:CustomValidator>
<script type="text/javascript">
function checkCheckBoxList(oSrc, args) {
var isValid = false;
$("#<%= CheckBoxList1.ClientID %> input[type='checkbox']:checked").each(function (i, obj) {
isValid = true;
});
args.IsValid = isValid;
}
</script>
And for a RadioButtonList
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one" ClientValidationFunction="checkRadioButtonList"></asp:CustomValidator>
<script type="text/javascript">
function checkRadioButtonList(oSrc, args) {
if ($("input[name='<%= RadioButtonList1.UniqueID %>']:checked").val() == null) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
</script>
Here is another solution that may be considered via Dado.Validators on GitHub.
<asp:CheckBoxList ID="cblCheckBoxList" runat="server">
<asp:ListItem Text="Check Box (empty)" Value="" />
<asp:ListItem Text="Check Box 1" Value="1" />
<asp:ListItem Text="Check Box 2" Value="2" />
<asp:ListItem Text="Check Box 3" Value="3" />
</asp:CheckBoxList>
<Dado:RequiredFieldValidator runat="server" ControlToValidate="cblCheckBoxList" ValidationGroup="vlgSubmit" />
Example codebehind.aspx.cs
btnSubmit.Click += (a, b) =>
{
Page.Validate("vlgSubmit");
if (Page.IsValid) {
// Validation Successful
}
};
https://www.nuget.org/packages/Dado.Validators/
Ref: Check if a checkbox is checked in a group of checkboxes in clientside
We can achieve this by C# also
bool Item_selected = false;
foreach (ListItem item in checkbox.Items)
{
if (item.Selected == true)
{
Item_selected = true;
}
}
if (!Item_selected )
{
//your message to user
// message = "Please select atleast one checkbox";
}
Loop through each of the items in ckBoxListReasons. Each item will be of type 'ListItem'.
The ListItem will have a property called 'Selected' that is a boolean. It's true when that item is selected. Something like:
Dim bolSelectionMade As Boolean = False
For Each item As ListItem in ckBoxListReasons.Items
If item.Selected = True Then
bolSelectionMade = True
End If
Next
bolSelectionMade will be set to true if the user has made at least one selection. You can then use that to set the Valid state of any particular validator control you like.

Why does ModalPopupExtender not show through javascript?

I followed several web resources to understand how to show a popup from client side, and I made this code:
<asp:ImageButton runat="server" ID="btnOk" ImageUrl="imagens/btnAlterar.gif" OnClientClick="btnOkClick()" />
<asp:LinkButton runat="server" ID="dummyForPopup" Visible="false"/>
<ajaxToolKit:ModalPopupExtender runat="server" BehaviorID="btnOkPopupBehavior" ID="MPXtender" TargetControlID="dummyForPopup" PopupControlID="pnlUpdateUserModal" BackgroundCssClass="modalBackground" OkControlID="btnCloseRequestUserUpdate" OnOkScript="userUpdReq_onOk()" />
function btnOkClick()
{
if(validateAll())
{
var behavior = $find('btnOkPopupBehavior');
if (behavior)
{
behavior.show();
}
else
{
var lblOutput = $get('<%= lblOutput .ClientID %>');
lblOutput .innerText = 'Couldn't find popup';
}
}
}
previously I had the modal popup linked to the ok button, it was working pretty well. Now I need some validation before opening the popup, and this code is not working anylonger =/
1) Your dummy button has to be visible = true, otherwise the javascript doesn't work properly. So set visible = true but disaply none with css:
<asp:LinkButton runat="server"
ID="dummyForPopup" style
="display:none" Visible="true" />
2) lblOutput .innerText = 'Couldn't find popup'; is a javascript error. You need to change it to: "Couldn't find popup"; (or use &apos;)
3) OnClientClick="btnOkClick()" should really say: OnClientClick="btnOkClick(); return false;"
4) Look for any other javascript errors on your page because those will stop the popup from workign properly.

Resources