I have a button which causes a popup to be created:
<ItemTemplate>
<asp:Button ID="viewHoursButton" runat="server" Text="View Hours" OnClick="viewHoursButton_OnClick" />
<ajaxToolkit:ModalPopupExtender ID="viewHoursPopup" runat="server"
TargetControlID="viewHoursButton"
PopupControlID="viewHoursPanel"
CancelControlID="closeInfoPanelButton2"
DropShadow="true">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="viewHoursPanel" runat="server" CssClass="infoPanel">
//content of panel including gridview
</asp:Panel>
</ItemTemplate>
The panel that pop's up has a gridview and when the button is pressed a SQL parameter is passed. :
protected void viewHoursButton_OnClick(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow row = btn.NamingContainer as GridViewRow;
SqlDataSource6.SelectParameters["nonScrumStoryId"].DefaultValue = storyGridView.DataKeys[row.RowIndex].Values[0].ToString();
var viewHoursGridView = storyGridView.FindControl("viewHoursGridView") as GridView;
if (viewHoursGridView != null)
{
viewHoursGridView.DataBind();
}
}
The issue is that the gridview isn't showing because there is no postback to the server. When you add a button to ajaxToolkit:ModalPopupExtender the postback is pevented. How do I get it back?
You can force postback with Javascript by attaching __doPostBack to an event.
function doClick(sender, e) {
__doPostBack(sender,e);
}
Hi i use this code Javascript to close the popup and refresh parent webform
Dim str_java As String = "<script language='javascript'>"
str_java += (" window.onunload = refreshParent; ")
str_java += (" function refreshParent() { ")
str_java += (" window.self.location.reload(true); } ")
str_java += (" window.close(); ")
str_java += ("</script>")
ScriptManager.RegisterStartupScript(Me, GetType(Page), "cerrarpagina", str_java, False)
this could help you
Related
I have a Repeater with a certain DataSource (consisting of a list of images). The Repeater holds ImageButtons.
The aspx:
<asp:Panel ID="panSearch" runat="server" ScrollBars="Vertical" BorderColor="#333333" BorderStyle="Inset" Width="500" Height="200">
<asp:Repeater ID="Repeater" runat="server">
<ItemTemplate>
<asp:ImageButton OnClick="imgSearchResult_Click" BackColor="#333333" ID="imgSearchResult" height="32" width="32" runat="server" ImageUrl='<%# Eval("ImageUrl") %>'/>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
Additionally, I have a TextBox, which has a TextChanged-event in code-behind. I do a few things in there and at the end, my Repeater's DataSource will be overwritten with a new List of images (those images are put into the ImageButtons).
Repeater.DataSource = ImageList;
Repeater.DataBind();
My problem: Whenever my Repeater.DataSource is changed, it "clicks" the first ImageButton inside the Repeater. How do I prevent that from happening?
Full code:
My TextBox:
<asp:TextBox ID="textSearch" runat="server" Width="80" OnTextChanged="textSearch_TextChanged" ForeColor="Black" />
My TextChanged event:
protected void textSearch_TextChanged(object sender, EventArgs e)
{
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images/ORAS"));
List<System.Web.UI.WebControls.Image> ImageList = new List<System.Web.UI.WebControls.Image>(filesindirectory.Count());
foreach (string item in filesindirectory)
{
System.Web.UI.WebControls.Image myImage= new System.Web.UI.WebControls.Image();
myImage.ImageUrl = (String.Format("~/Images/ORAS/{0}", System.IO.Path.GetFileName(item)));
ImageList.Add(myImage);
}
Repeater.DataSource = ImageList;
Repeater.DataBind();
}
When I click on an ImageButton inside the Repeater (which is executed when the text in my TextBox is changed):
protected void imgSearchResult_Click(object sender, ImageClickEventArgs e)
{
var selectedImage = sender as ImageButton;
if (img1.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img1.ImageUrl = selectedImage.ImageUrl;
}
else if (img2.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img2.ImageUrl = selectedImage.ImageUrl;
}
else if (img3.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img3.ImageUrl = selectedImage.ImageUrl;
}
else if (img4.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img4.ImageUrl = selectedImage.ImageUrl;
}
else if (img5.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img5.ImageUrl = selectedImage.ImageUrl;
}
else if (img6.ImageUrl == "~/Images/ORAS/Empty/000.png")
{
img6.ImageUrl = selectedImage.ImageUrl;
}
else
{
ErrorMessage("Please remove one Image first!", true);
}
}
Pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
img1.ImageUrl = "~/Images/ORAS/Empty/000.png";
img2.ImageUrl = "~/Images/ORAS/Empty/000.png";
img3.ImageUrl = "~/Images/ORAS/Empty/000.png";
img4.ImageUrl = "~/Images/ORAS/Empty/000.png";
img5.ImageUrl = "~/Images/ORAS/Empty/000.png";
img6.ImageUrl = "~/Images/ORAS/Empty/000.png";
LoadImages();
}
}
(LoadImages is almost 1:1 what's in my TextChanged function)
I really am not sure how (why) ASP.NET WebForms does it, but if you hit Enter and the form posts back, it will find the first control that implements IPostBackEventHandler and execute whatever event is bound to that. ImageButton implements it and so that's why it keeps firing the click event even though you didn't click on it. And, once again, only if you hit Enter.
I think that behaviour happens because the data posted back - __EVENTTARGET and __EVENTARGUMENT - are empty. Then ASP.NET goes bonkers.
You can solve it by putting a dummy button at the top of the page (or masterpage) and hide it using the style attribute. so:
<asp:Button ID="dummy" runat="server" style="display:none" />
Then in the init or load of your page (or masterpage) put
Form.DefaultButton = dummy.UniqueID;
That will force the button to capture the enter press instead of the arbitrary image button.
I have a GridView which has these two controls:
<asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' OnClick="btnShow_Click" />
<asp:LinkButton runat="server" ID="btnShow2" CssClass="btnSearch2" Text="View Allst" CommandName="ViewAll" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' PostBackUrl="JavaScript:void(0);" OnClientClick="return false;" OnClick="btnShow_Click">View Alls</asp:LinkButton>
code-behind:
protected void btnShow_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.Button btn1 = (System.Web.UI.WebControls.Button)(sender);
string strCA = btn1.CommandArgument;
string strCN = btn1.CommandName;
int index = 0;
if (strCN == "ViewAll")
{
index = Convert.ToInt32(strCA);
DataTable cacheTable = HttpContext.Current.Cache["ResultsTable"] as DataTable;
string column = cacheTable.Rows[index].Field<string>("Guideline");
string test = BookingResults.Rows[index].Cells[7].Text;
string html = HttpUtility.HtmlDecode(column);
ResultsDiv.InnerHtml = html;
}
}
JQuery:
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
e.preventDefault();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
$(".btnSearch2").click(function (e) {
e.preventDefault();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
$("#popupContactClose").click(function () {
disablePopup();
});
$("#backgroundPopup").click(function () {
disablePopup();
});
//Press Escape event!
$(document).keypress(function (e) {
if (e.keyCode == 27 && popupStatus == 1) {
disablePopup();
}
});
});
var popupStatus = 0;
//loading popup with jQuery magic!
function loadPopup() {
//loads popup only if it is disabled
if (popupStatus == 0) {
$("#backgroundPopup").css({
"opacity": "0.7"
});
$("#backgroundPopup").fadeIn("slow");
$("#popupContact").fadeIn("slow");
popupStatus = 1;
}
alert(popupStatus);
}
//disabling popup with jQuery magic!
function disablePopup() {
//disables popup only if it is enabled
if (popupStatus == 1) {
$("#backgroundPopup").fadeOut("slow");
$("#popupContact").fadeOut("slow");
popupStatus = 0;
}
alert(popupStatus);
}
//centering popup
function centerPopup() {
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupContact").height();
var popupWidth = $("#popupContact").width();
//centering
$("#popupContact").css({
"position": "absolute",
"top": windowHeight / 2 - popupHeight / 2,
"left": windowWidth / 2 - popupWidth / 2
});
//only need force for IE6
$("#backgroundPopup").css({
"height": windowHeight
});
}
HTML that displays the popup:
<div id="popupContact">
<a id="popupContactClose" title="Close Window">x</a>
<h3>Booking Guidelines</h3>
<asp:Panel ID="Panel1" runat="server" style="vertical-align:top" ScrollBars="Vertical" Height="300px" ForeColor="Black">
<div id="ResultsDiv" runat="server" style="vertical-align:top" > </div>
</asp:Panel>
</div>
<div id="backgroundPopup"></div>
The GridView generates multiple rows, where each row the button will have a different INDEX number to reference the session table being used to populate ResultsDiv.InnerHtml = html;.
When I click on btnShow Button it displays the alert and shows the popup with the updated ResultsDiv.InnerHtml = html; by using the code-behind for a split second and does a postback and reloads the page.
When I click 'btnShow2' LinkButton it displays the alert and shows the popup and does not do a postback. The only issue I am having is, it doesn't access the code-behind to update ResultsDiv.InnerHtml = html; so it is always displaying the same result no matter what row the button is clicked.
How do I modify my code so that it updates the ResultsDiv.InnerHtml = html; and displays the popup every time the button is clicked on any of the row and does NOT do a postback?
If You Remove Both
OnClientClick="return false;" and
PostBackUrl="JavaScript:void(0);" then definitely it will postback.
You can observe your HTML generated/rendered if you set both attributes with Postback event
WebForm_DoPostBackWithOptions which should be something like
javascript:__doPostBack('BookingResults$ctl02$btnShow2','')
View Alls
You have OnClientClick="return false;". That cancels the postback. To fix it, remove that attribute from your LinkButton declaration.
Also, not sure what PostBackUrl="JavaScript:void(0);" does. I've never seen someone to do that. You might try eliminating that if it's not necessary.
My problem is in asp.net Button control and DropDownList.
I have a Button called ApplyButton and a DropDownList called FilterCombo.
<asp:Button ID="ApplyButton" runat="server" Text="Apply Filter" OnClick="ApplyButton_Click" />
<asp:DropDownList ID="FilterCombo" runat="server" ></asp:DropDownList>
I want to call a method which accept a int as a parameter using my DropDownList's (FilterCombo) SelectedIndex In ApplyButton's OnClick event. But Onclick event of Button is not firing when I click on the Button. But it works if I set Button's UseSubmitBehavior="false".
<asp:Button ID="ApplyButton" runat="server" Text="Apply Filter" OnClick="ApplyButton_Click" UseSubmitBehavior="false" />
Now the OnClick method is firing well. But the problem is FilterCombo.SelectedIndex always returns 0. Why can't I fire the Onclick event without setting UseSubmitBehavior="false" and How can I get the correct SelectedIndex of FilterCombo ?
Here is the backend code for Page_Load,
protected void Page_Load(object sender, EventArgs e)
{
LeftSideBarHolder.Controls.Add(Page.LoadControl("~/Pages/Common_wa/LeftPanel.ascx"));
HeaderHolder.Controls.Add(Page.LoadControl("~/Pages/Common_wa/Header.ascx"));
try
{
string columns = Request["columns"];
string[] arr = columns.Split(';');
pkey = bool.Parse(arr[0]);
leader = bool.Parse(arr[1]);
type = bool.Parse(arr[2]);
level = bool.Parse(arr[3]);
state = bool.Parse(arr[4]);
dueDate = bool.Parse(arr[5]);
}
catch (Exception ex)
{
//do nothing : This is the parameterless request
}
if (!IsPostBack)
{
Owner = int.Parse(Session["userID"].ToString());
ViewState["PreviousPage"] = Request.UrlReferrer;
LoadFilters();
if (pkey) pKeyCheckBox.Checked = true;
if (leader) LeaderCheckBox.Checked = true;
if (type) TypeCheckBox.Checked = true;
if (level) LevelCheckBox.Checked = true;
if (state) StateCheckBox.Checked = true;
if (dueDate) DueDateCheckBox.Checked = true;
}
try
{
DTO.Search.SearchResult SearchResult_new = (DTO.Search.SearchResult)Session["SearchResults"];
Result = SearchResult_new.Result;
}
catch (Exception ex)
{
}
}
Code for LoadFilters() - Used to load data to the FilterCombo
private void LoadFilters()
{
SearchUtils util = new SearchUtils();
int Owner = int.Parse(Session["userID"].ToString());
DataSet filters = util.GetFiltersOfOwner_AsDataSet(Owner);
FilterCombo.DataSource = filters;
FilterCombo.DataValueField = "Id";
FilterCombo.DataTextField = "Name";
FilterCombo.DataBind();
}
OnClick event of ApplyButton
protected void ApplyButton_Click(object sender, EventArgs e)
{
SearchUtils util = new SearchUtils();
int Id = int.Parse(FilterCombo.SelectedItem.Value.ToString());
SearchFilter filter = util.GetFilter(Id);
string Columns = filter.Columns;
string[] arr = Columns.Split(';');
pkey = bool.Parse(arr[0]);
leader = bool.Parse(arr[1]);
type = bool.Parse(arr[2]);
level = bool.Parse(arr[3]);
state = bool.Parse(arr[4]);
dueDate = bool.Parse(arr[5]);
Response.Redirect("SearchResult_new.aspx?columns=" + pkey + ";" + leader + ";" + type + ";" + level + ";" + state + ";" + dueDate + "");
}
Update : I think i found the reason. But don't know a solution..
My Button and DropDownList are in a Div which is working as a jQuery Dialog which is invoke by a JavaScript function.
<%-- Load Filter Dialog Box --%>
<div id="loadFilterDialog" title="Apply Filter" style="display: none">
<div class="BodyPanelDiv">
<asp:DropDownList ID="FilterCombo" runat="server"></asp:DropDownList>
</div>
<div class="BottomPanelDiv" align="Right">
<asp:Button ID="ApplyButton" runat="server" Text="Apply Filter" OnClick="ApplyButton_Click" UseSubmitBehavior="false" />
<asp:Button ID="CancelButton2" runat="server" Text="Cancel" OnClientClick="return closeDialog(2); return false;" />
</div>
</div>
<%-- End of Load Filter Dialog Box --%>
Here is the JavaScript which invokes the Dialog
//Display JQuery Dialog
function showDialog() {
$("#loadFilterDialog").dialog({
draggable: true,
resizable: false,
width: 350,
height: 150,
minHeight: 10,
minwidth: 10
});
return false;
}
This answer is marked in my favorites. To use .Net postbacks with jQuery dialog, you have to play around with forms. The good thing is it's a simple fix; but I keep this solution bookmarked as it's one of those that is a bit obscure.
jQuery UI Dialog with ASP.NET button postback
So your above code becomes:
//Display JQuery Dialog
function showDialog() {
$("#loadFilterDialog").dialog({
draggable: true,
resizable: false,
width: 350,
height: 150,
minHeight: 10,
minwidth: 10
});
$("#loadFilterDialog").parent().appendTo($("form:first"));
return false;
}
I have a Panel in an UpdatePanel, a Button and a TextBox.
<asp:UpdatePanel ID="updatepanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="commentBox" Rows="1" Columns="60" placeholder="Add a comment..." TextMode="MultiLine" ClientIDMode="Static" runat="server"></asp:TextBox>
<asp:LinkButton ID="commentButton" runat="server" OnClick="commentButton_Click"> CommentButton </asp:LinkButton>
<asp:Panel ID="commentPanel" runat="server"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
on Button Click I am trying add what's in the TextBox to the Panel like this
Literal myComment = new Literal();
myComment.Text = "<p>"+commentBox.Text+"</p><br />";
commentPanel.Controls.Add(myComment);
This adds whats currently in the TextBox, but what was there in the panel gets removed.
So every time it starts from 0 count for controls in the panel. what am I missing?
you can check this out:
List<Literal> persistControls = new List<Literal>();
protected void Page_Load(object sender, EventArgs e)
{
// if you already have some literal populated
if (Session["persistControls"] != null)
{
// pull them out of the session
persistControls = (List<Literal>)Session["persistControls"];
foreach (Literal ltrls in persistControls)
commentPanel.Controls.Add(ltrls); // and push them back into the page
}
}
protected void commentButton_Click(object sender, EventArgs e)
{
Literal myComment = new Literal();
myComment.Text = "<p>" + commentBox.Text + "</p><br />";
commentPanel.Controls.Add(myComment);
persistControls.Add(myComment);// add it to the list
Session["persistControls"] = persistControls; // put it in the session
}
Literal comment = new Literal();
comment.Text="";
Panel1.Controls.Add(comment);
if (Panel1.Controls.Contains(comment))
{
comment.Text = comment.Text + "<p>" + commentbox.Text + "</p>";
}
I put a hyperlink inside a datalist..
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server">'<%# Eval("ThreadTitle") %>'</asp:HyperLink>
<br />
<br />
</ItemTemplate>
I want it to enable it to be pressed so that the datalist event will be triggered and transfer me to another page:
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
Server.Transfer("AnswerQuestion.aspx?x=" + DataList1.DataKeyField + "&question=" + DataList1.SelectedValue + "&time=" + DateTime.Now);
}
Unfortunately, the link seems to be disabled and I cant press on it to trigger the DataList Selected event..
How can I make the hyperlink active ?
If you want to trigger a selecteditemchaned event use a LinkButton instead of hyperlink.
<asp:DataList ID="DataList1" runat="server"
onselectedindexchanged="DataList1_SelectedIndexChanged">
<ItemTemplate>
<asp:LinkButton ID="sjdj" runat="server" CommandName="Select">
<%# Container.DataItem %></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
In the code behind have
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
Server.Transfer("~/jjtestjj.aspx?" + DataList1.DataKeyField);
}
why arent you using the Hyperlink as a hyperlink?
You can set the NavigationURL and Text using the OnItemDataBound (or equivalent) event.
this code works with an asp:Repeater:
protected void Row_DataItem(object row, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.AlternatingItem || args.Item.ItemType == ListItemType.Item)
{
var item = (DataItemPOCO)args.Item.DataItem;
var link = (HyperLink)args.Item.FindControl("HyperLink1");
link.Text = item.LinkText;
link.NavigateUrl = item.URL;
}
}