Checkboxlist in hidden DIV - asp.net

I have a CheckboxList within a DIV. The DIV appears as a modal popup when a button is clicked. Then the user checks off any number of items in the checkboxlist and clicks OK. This hides the div.
once the user clicks the save button on the main form, I need to pass parameters to a stored procedure based on which items in the checkboxlist were clicked, but they are always set to unchecked when I run the save code. I'd love some thoughts on how to do this properly.
Thanks
JQuery:
$(document).ready(function () {
$('#<%=txtLANG.ClientID %>').click(function () {
$("#overlay-back").dialog({
resizable: false,
modal: true,
width: 500,
height: 400,
buttons: {
OK: function () {
GetLanguages();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
});
Save Method in CodeBehind
private void Save()
{
List<string> lstItemsChecked = new List<string>();
for (int i = 0; i < chkTopLanguages.Items.Count; i++)
{
if(chkTopLanguages.Items[i].Selected)
lstItemsChecked.Add(chkTopLanguages.Items[i].Value);
}
//stored proc call
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Save();
}
ASPX Code for DIV popup and CheckBoxList
<div id="overlay-back" style="display:none;">
<td rowspan="3" valign="top">
<asp:CheckBoxList ID="chkTopLanguages" TextAlign="Right" runat="server" />
<br />
<asp:TextBox runat="server" ID="txtOtherLanguages" Text="Other Languages..."></asp:TextBox>
</td>
</div>

maybe this happens because the when you close the popup, the controls on the popup are not accessible. I don't know the exact cause but you can create an array variable in javascript. Whenever you check or uncheck a checkbox; with the help of javascript, you modify that variable to what all variables are set or not.
I used modal popup way long back and there was an issue like that only.
This approach might not be optimal but will work for sure.

Try setting the AutoPostBack to false:
<asp:CheckBoxList ID="chkTopLanguages" TextAlign="Right" runat="server" AutoPostBack="false" />
For the CheckBoxList control.

Related

Why I cant get selected radio button from asp:RadioButtonList control?

I generate radio buttons:
foreach (string header in headers)
{
XMLHeaders.Visible = true;
rdHeaders.Items.Add(header);
}
Here is ASP code:
<asp:Panel ID="XMLHeaders" runat="server" Visible="false" CssClass="group">
<asp:RadioButtonList ID="rdHeaders" runat="server" RepeatLayout="Flow" RepeatDirection ="Vertical">
</asp:RadioButtonList>
<div class="row1" style="padding: 3px; text-align: left">
<asp:Button Text="B" ID="btnDescColumn" runat="server" OnClick="SetDescPoint" CausesValidation="False"/>
</div>
</asp:Panel>
Here how it looks in the view:
When B button is selected post back occured and this function is fired:
protected void SetDescPoint(object sender, EventArgs e)
{
var columnDesc = rdHeaders.SelectedItem;
}
At the event hendler above I try to get the selected radio button but, I get null.
How do I get selected radio button ?
in your page load event where you generate your radio buttons, wrap it with a Page.IsPostBack check like so:
if (!IsPostBack)
{
foreach (string header in headers)
{
XMLHeaders.Visible = true;
rdHeaders.Items.Add(header);
}
}
This will ensure your radiobutton list is not regenerated on your page postback. What is most likely happening is the postback is rebuilding the radiobuttonlist which clears any previous selections if you have viewstate disabled.

Where to catch user control properties being wrapped to be loaded inside a modal?

I have a user control which has a public property (e.g. AlarmID) and this control is wrapped inside a div and when user presses a button on the page, in code-behind the public property of that user control becomes set. then a ScriptManager.RegisterStartupScript is called to show a modal popup which is a div wrapping that control.
My problem is that although in code-behind I first set the public property of that user control, but when the modal popup shows that user control, I cannot access that property
I used Control_PreRender, and Control_Load events but none of them were able to show the correct value of that property in a label inside that control.
For more clarification, here is my code in the code-behind of the control:
protected void Control_Load(object sender, EventArgs e)
{
lblAlarmCode.Text = alarmID.ToString();
}
public int AlarmID
{
get
{
return this.alarmID;
}
set
{
this.alarmID = value;
}
}
What is the exact life-cycle event in which I can catch the property to be shown correctly by that label?
Thanks
Make sure that the modal is attached to the <form> element on the page otherwise it will not be a part of the page lifecycle at all.
Just as a sample, not saying this is your code, but I had to use something similar in order to have <asp:Textbox> and <asp:Button> controls to be brought back and forth across the Request
ASPX code:
<asp:Panel runat="server" ID="pnlWorkItem">
<fieldset>
<legend></legend>
<label>Job Code</label>
<asp:DropDownList runat="server" ID="ddlJobCode" Width="50%" />
<label>Hours</label>
<asp:TextBox runat="server" ID="txtHours" />
</fieldset>
<fieldset>
<legend></legend>
<p><asp:Button runat="server" ID="btnAddWorkItem" OnClick="btnAddWorkItem_Click" text="Add Work Item" /></p>
</fieldset>
</asp:Panel>
Javascript:
$(function () {
var workItemPanel = $("#<%= pnlWorkItem.ClientID %>");
workItemPanel.hide();
$("#add-work").on("click", function () {
$(workItemPanel).dialog({
width: 450,
height: 300
}).parent().appendTo($("form:first"));
});
});
It will append your element to the form element generated by ASP.net and should have your properties set and carried across.
One solution is to set the label in setter. However there might be other solutions but this ways is just working.

Modal ASP.net user control

I have a web form app where a couple of user-controls have been developed and placed on a page where a customer is building an order. The user-controls are pretty extensive in what they do, causing post-backs, etc.
I'd like to display them in a modal fashion without putting them in a separate page (if possible). So therein lies my question.
Is it possible to place user-controls within divs/panels, display them modally and keep them displayed modally (even through postbacks) until the user clicks a button on the control to dismiss it?
I'm basically looking at the modal option because I need to disable the rest of the form while the user is dealing with the sections the user-control is on. So I'm looking for a best-practice approach I suppose and some nudges in the right direction for this.
Thanks!
ADDITION:
I wanted to update this with the code I wrote in hopes that it might help somebody else and also if there is a better way to implement this, then I'm all ears too.
The basics of this is that I'm passing everything back and forth between my user control and the container page through session vars. I use this to tell the container page whether or not the user control is "finished" and until the flag is set to true, the container page just keeps re-displaying the user control modally on each postback. Seems to work well so far.
Markup:
<%# Register Src="../controls/mylabel.ascx" TagName="mylabel" TagPrefix="uc1" %>
<div style="width: 100%;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="ButtonAddToCart" runat="server" Text="Add to cart" OnClick="ButtonAddToCartClick" />
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlOutput" Visible="False" runat="server" Width="500px">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<div style="visibility: hidden;">
<asp:Button ID="ButtonHidden" runat="server" Text="Button" />
</div>
<asp:Panel ID="pnlDownload" Visible="False" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div style="width: 100%;">
<uc1:mylabel ID="mylabel1" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
Code behind:
protected void Page_PreRender(object sender, EventArgs e)
{
InitializeControls();
}
protected void Page_Load(object sender, EventArgs e)
{
InitializeControls();
}
private void InitializeControls()
{
DisplayDownloadPanel(!SessionDownloadComplete);
if (SessionDownloadItemNumber != string.Empty)
{
Label1.Text = SessionDownloadItemNumber != "CANCEL" ? "Item ordered from control was: [" + SessionDownloadItemNumber + "]" : "Order was canceled.";
pnlOutput.Visible = true;
}
}
protected void ButtonAddToCartClick(object sender, EventArgs e)
{
bool haveWeSomeText = string.IsNullOrEmpty(TextBox1.Text) == false;
if (haveWeSomeText == true)
{
SessionDownloadComplete = false;
DisplayDownloadPanel(true);
}
}
private void DisplayDownloadPanel(bool show)
{
pnlDownload.Visible = show;
if (show == true)
{
ModalPopupExtender1.Show();
}
else
{
ModalPopupExtender1.Hide();
}
}
private string SessionDownloadItemNumber
{
get { return Session["DownloadItemNumber"] != null ? Session["DownloadItemNumber"].ToString() : string.Empty; }
}
private bool SessionDownloadComplete
{
get { return Session["DownloadComplete"] == null || Convert.ToBoolean(Session["DownloadComplete"]); }
set { Session["DownloadComplete"] = value; }
}
Have a look at ASP.NET Ajax Toolkit Modal popup extender
Take a look at the jQuery UI dialog.
It is a good solution for cross browser modal dialogs in the browser.
<script>
$(function() {
$( ".dialogClass" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
There are a few initial hiccups integrating it with asp.net. But all those are very well documented here on stackover flow itself.

How to display value in the SimpleModal's dialog?

my question is really simple. I have a asp.net button. I can use it to call the simpleModal and have a dialog displayed. Now, I added a label control in the dialog, and would like this label to display some value. What should I do?
Here is my codes
$('#<%= btnOpen.ClientID %>').click(function(e) {
e.preventDefault();
$('#content').modal({
onOpen: function(dialog) {
dialog.overlay.fadeIn('slow', function() {
dialog.data.hide();
dialog.container.fadeIn('slow', function() {
dialog.data.slideDown('slow');
});
});
},
onClose: function(dialog) {
dialog.data.fadeOut('slow', function() {
dialog.container.slideUp('slow', function() {
dialog.overlay.fadeOut('slow', function() {
$.modal.close(); // must call this!
});
});
});
}
});
e.preventDefault();
// return false;
});
<asp:Button ID="btnOpen" runat="server" Text="ASP.NET Open"/>
<div id="content" style="display: none;">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
I assume since you said that your question is simple that you just have an unfamiliarity with jQuery. You can put this in your click function, or in the $(document).ready function, depending on your full requirements:
var yourValue = ; // put your function or value here
$('#Label1').text(yourValue);
Note: You'll need to use .html instead of .text if you have a string with tags, but .text is faster.
Lol, I am answering my own question again, but I will give credit to mNVhr tho.
I finally get the whole thing work. The trick for asp.net button to fire a postback, along with javascript's postback, is to put the asp.net button into an update panel. Here is the code I have
For the javascript part:
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery.simplemodal-1.3.5.js" type="text/javascript"></script>
<script type="text/javascript">
function myOpen() {
$('#content').modal({
onOpen: function(dialog) {
dialog.overlay.fadeIn('slow', function() {
dialog.data.hide();
dialog.container.fadeIn('slow', function() {
dialog.data.slideDown('slow');
});
});
},
onClose: function(dialog) {
dialog.data.fadeOut('slow', function() {
dialog.container.slideUp('slow', function() {
dialog.overlay.fadeOut('slow', function() {
$.modal.close();
});
});
});
}
});
}
function myClose() {
$.modal.close();
}
</script>
For the HTML markup
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnOpen" runat="server" Text="Open" OnClick="btnOpen_Click" OnClientClick="myOpen();" />
</ContentTemplate>
</asp:UpdatePanel>
<div id='content' style="display: none">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<input id="Button2" type="button" value="Close" onclick="myClose();" />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
For the code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
private void CloseDialog()
{
string script = string.Format(#"myClose()");
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "1")
CloseDialog();
else
Label2.Text = TextBox1.Text;
}
protected void btnOpen_Click(object sender, EventArgs e)
{
TextBox1.Text = DateTime.Now.ToString();
UpdatePanel1.Update();
}
I hope this tiny code can help those asp.net developer who want to use the nice jQuery in their projects.
As you can see, from the above codes.
When I click on the btnOpen button, two postbacks fired. One is from the asp.net code behind, which assign current datetime to the textbox control inside the modal dialog. The second postback is from the javascript, which open the modal dialog. The asp.net button has to be inside the update panel. Otherwise, the modal dialog will only stay for about 0.5 second.
When I click on the btnSave inside the modal dialog. Postback also occurred. I have a little logic here. When the textbox's value is 1, I call the closeDialog() function. When the value is other numbers, the modal dialog stay opening, and the label control inside the dialog will display the number from the text box.
jQuery is nice, but as a .Net developer, it is just new, and sometimes difficult for me to understand it, especially for the conflict of postbacks between javascript and .net.
I hope this answer is helpful.

JQuery DIalog and ASP.NET Repeater

I have an ASP.NET repeater that shows a list of items with a delete LinkButton.
I want to setup the Delete LinkButtons to show a JQuery Dialog for a confirmation. If the "OK" button is clicked, I want to do the postback.
The obvious problem is that each LinkButton in the repeater will have it's own ID and I don't want to have to duplicate all the javascript for the dialog.
Suggestions ?
The solution is not so simple. You must have the ability to call the original callback function after pressing the Ok button of jQuery UI Dialog.
First you need a generalized js function for showing the dialog:
function showConfirmRequest(callBackFunction, title, content)
{
$("#divConfirm").html(content).dialog({
autoOpen: true,
modal: true,
title: title,
draggable: true,
resizable: false,
close: function(event, ui) { $(this).dialog("destroy"); },
buttons: {
'Ok': function() { callBackFunction(); },
'Cancel': function() {
$(this).dialog("destroy");
}
},
overlay: {
opacity: 0.45,
background: "black"
}
});
}
I supposed the presence of a div like
<div id="divConfirm"></div>
On c# code-behind you have to register the previous client function, passing the original asp.net callbackFunction of your control as parameter (I generalized):
protected void AddConfirmRequest(WebControl control, string title, string message)
{
string postBackReference = Page.ClientScript.GetPostBackEventReference(control, String.Empty);
string function = String.Format("javascript:showConfirmRequest(function() {{ {0} }}, '{1}', '{2}'); return false;",
postBackReference,
title,
message);
control.Attributes.Add("onclick", function);
}
Through the method GetPostBackEventReference you have the ability to retrieve the postback function that asp.net assign to the control.
Now, on Repeater ItemDataBound, retrieve the control that execute the delete and pass it to this function:
<asp:Repeater ID="repeater" runat="server" OnItemDataBound="repeater_OnItemDataBound">
...
<ItemTemplate>
...
<asp:Button ID="btnDelete" runat="server" Text="Delete" />
...
</ItemTemplate>
</asp:Repeater>
and the code:
protected void repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
WebControl btnDelete = ((WebControl)e.Item.FindControl("btnDelete"));
AddConfirmRequest(btnDelete, "Confirm delete", "Are you sure? Really???");
}
}
I hope this helps.
<asp:GridView ... CssClass="mygridview"></asp:GridView>
and
$('table.mygridview td a').whatever()
That will allow you to work with all the link buttons simultaneously.
You can make it like this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
...
<asp:LinkButton OnClick="DoSomething" OnClientClick="return ConfirmDelete();" ID="btnConfirm" runat="server" CssClass="button" Text="Delete"></asp:LinkButton><br /><br />
</ItemTemplate>
</asp:Repeater>
<script>
function ConfirmDelete() {
return confirm("Delete this record?");
}
</script>
or i think you could also make it like this:
<script>
$(function() {
$(".button").click(function() {
return confirm("Delete this record?");
});
});
</script>
in the ConfirmDelete Method, you can define your jQuery Confirm dialog
The question is definitely answered by tanathos, but I have another option working that avoids scripting in the code-behind if you are so inclined. I just hid the asp delete button using display:none and added a delete button that invokes the confirmation dialog and clicks the hidden asp delete button if the delete is confirmed.
The HTML in the repeater:
<ItemTemplate>
...
<td>
Delete
<asp:Button ID="DeletePolicyButton" runat="server" OnCommand="OnDeleteCommand" CommandArgument="Argument" Text="Delete" CssClass="delete-button" />
</td>
...
</ItemTemplate>
The CSS:
.delete-button
{
display: none;
}
The javascript:
// make the dummy button look like a button
$("a.dummy-delete-button").button({
icons: {
primary: "ui-icon-trash"
}
});
// create the dialog
var deleteDialog = $('<div>Are you sure you want to remove this policy?</div>')
.dialog({
autoOpen: false,
modal: true,
title: 'Delete Policy'
});
// handle click event to dummy button
$("a.dummy-delete-button").click(function (e) {
// don't follow the href of the dummy button
e.preventDefault();
// get a reference to the real ASP delete button
var button = $(this).closest('td').find('.dummy-delete-button');
deleteDialog.dialog({
buttons: {
// handle delete. Note: have to defer actual button click until after close
// because we can't click the button while the modal dialog is open.
"Delete": function () { deleteDialog.bind("dialogclose", function () { button.click() }); $(this).dialog("close"); },
// handle close
"Cancel": function () { $(this).dialog("close"); }
}
});
deleteDialog.dialog("open");
});
Hy,
First you should use Jquery Dialog or other clienside dialogs, it's more cooler.
You should have an html element on the page to invoke the Jquery dialog popup.
<div class="Popup"></div>
<script>
var confirm = false;
function ConfirmDelete(doPostback) {
$(".Popup").dialog(){ /* threat the dialog result , set confirm variable */ };
if(confirm) {
__doPostback(); }
else return false;
}
</script>
On the part where i put the comented sentence you can put code to handle the dialog result.
You could find info from the link above.
The function is returning false and because of that it blocks the execution of the server side code (the async postback).
The Button should look like:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton OnClientClick="ConirmDelete(<#%GetPostbackReference()%>)" CommandArgument = "<%# DataBinder.Eval(Container.DataItem, "Id") %>" OnClick="btnConfirm_Click" ID="btnConfirm" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
On the CommandArgument property i set the id of the item wich are binded to the repeater.
In this way on the btnConfirm_Click event you have acces to this paramater
void btnConfirm_Click(object sender, CommandEventArgs e)
{
e.CommandArgument -> you will find the id an you can execute the delete
}
You should have on the code behind:
protected string GetPostbackReference()
{
return Page.ClientScript.GetPostBackEventReference(btnConfirm, null);
}
This function is invoked on the binding of the element and returning the current controls postback method wich will look like __doPostback(source, param)
This is a javascript method wich you could excute easilly,and you have full control of the postbacks.
On clientside you can decide whether or not to call this postback event.
PS: If something is unclear post here a question and i will update the answer.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
...
<asp:LinkButton OnClick="DoSomething" OnClientClick="return ConfirmDelete();" ID="btnConfirm" runat="server" CssClass="button" Text="Delete"></asp:LinkButton><br /><br />
</ItemTemplate>
</asp:Repeater>
<script>
function ConfirmDelete() {
return confirm("Delete this record?");
}
</script>

Resources