Why is LinkButton not executing the Click function from code behind - c#

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.

Related

Replace javascript confirm dialog box with jquery confirm dialog

I am trying to write simple jquery confirm dialog with two buttons: delete and cancel. When dialog was written with javascript, everything worked well. Now cancel button works but delete button does not delete anything and just cancels deletion. I want commandname to call cmddelete property which will delete row.
I am using this example: http://www.codeproject.com/Tips/616118/jQuery-confirmation-in-ASP-NET-GridView
Csharp code:
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex;
switch (e.CommandName)
{
case "CmdDelete":
rowIndex = (((LinkButton)e.CommandSource).Parent.Parent as GridViewRow).RowIndex;
DeleteItem(ViewData.List[rowIndex].ID);
Gridview:
<asp:LinkButton ID="btnDelete" runat="server" CommandName="CmdDelete"
Text="delete" OnClientClick="javascript:return deleteItem(this.name);" ></asp:LinkButton>
Javascript code:
function deleteItem(CmdDelete)) {
var dialogTitle = 'Message from the webpage';
$("#deleteConfirmationDialog").html('<p><span class="ui-icon " +
"ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>" +
"Please click delete to confirm deletion.</p>');
$("#deleteConfirmationDialog").dialog({
title: dialogTitle,
buttons: {
"Delete": function () { __doPostBack(CmdDelete, '');
$(this).dialog("close"); },
"Cancel": function () { $(this).dialog("close"); }
}
});
$('#deleteConfirmationDialog').dialog('open');
return false;
}

How to use a button to populate data without doing a postback

I have the following ASP.net button inside my GridView:
<asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' />
The code-behind is:
protected void btnShow_Command(object sender, CommandEventArgs e)
{
int index = 0;
if (e.CommandName == "ViewAll")
{
index = Convert.ToInt32(e.CommandArgument);
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;
}
}
The ResultsDiv is shown in a popup using the JQuery:
//CONTROLLING EVENTS IN jQuery
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
alert($(this).val() + " Clicked");
e.preventDefault();
//centering with css
centerPopup();
//load popup
loadPopup();
});
});
When I navigate to the page, the generated HTML looks as follow (there are multiple rows with the same button in the column):
<input type="button" name="ctl00$ctl33$g_36ed1b14_1f08_43fb_8099_eb3423a33ed9$BookingResults$ctl224$btnShow" value="View All" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl33$g_36ed1b14_1f08_43fb_8099_eb3423a33ed9$BookingResults$ctl224$btnShow", "", true, "", "", false, true))" id="ctl00_ctl33_g_36ed1b14_1f08_43fb_8099_eb3423a33ed9_BookingResults_ctl224_btnShow" class="btnSearch" />
What is happening now, is when I click the View All button it displays the alert, when I click OK, it displays the popup for a split second and refreshes the page.
How can I modify the code-behind/JQuery so that I can click on any of the button, and it will display the alert and show the popup every time and not do a postback?
I think the first thing you need to do even before alert is e.preventDefault();
//CONTROLLING EVENTS IN jQuery
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
e.preventDefault();
e.stopproPagation();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
});
As what i think that the alert lets the event do its default job first.

ASP.NET Button OnClick not firing without setting UseSubmitBehavior="false"

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;
}

How to Uncheck All Radio Button inside GridView using JQuery?

I have a Radio Button inside GridView. I want to Uncheck all the asp.net Radio Button except the current Selected one using JQuery. I have tried but no results..!
HTML Markup:
<ItemTemplate>
<asp:RadioButton ID="rdbUser" runat="server" kID='<%# Eval("kID")%>' class="rdbUser" />
</ItemTemplate>
Code:
$(document).on("click", ".rdbUser", function() {
var selectedRadio = $(this).attr('id');
//var newrdo = $("input:radio.rdbUser:checked");
//$(".rdbUser").prop('checked', false);
//$('#' + selectedRadio).prop('checked', true);
//$('input:radio[class=rdbUser]').prop('checked', false);
// $('.rdbUser').removeAttr('checked');
var kID = $(this).attr('kID');
$("#ctl00_ContentPlaceHolder1_hdnKioskID").val(kID);
alert("selected Radio : " + kID);
});
On SeeingMarkup in Chrome:
Checked RadioButton:
<span class="rdbUser" kid="2"><input id="ctl00_ContentPlaceHolder1_GridView1_ctl03_rdbUser" type="radio" name="ctl00$ContentPlaceHolder1$GridView1$ctl03$rdbUser" value="rdbUser"></span>
Unchecked RadioButton:
<span class="rdbUser" kid="21"><input id="ctl00_ContentPlaceHolder1_GridView1_ctl05_rdbUser" type="radio" name="ctl00$ContentPlaceHolder1$GridView1$ctl05$rdbUser" value="rdbUser"></span>
Try this,
$(document).on("click", ".rdbUser", function() {
// to uncheck all radios which are not checked
$("input[type=radio].rdbUser").prop("checked", false);
$(this).prop('checked',true);// check the current one only
});
I think you should use RadioButton.GroupName property.
Use the GroupName property to specify a grouping of radio buttons to create a mutually exclusive set of controls. You can use the GroupName property when only one selection is possible from a list of available options.
When this property is set, only one RadioButton in the specified group can be selected at a time.
However you can try this code using jquery
$(document).on("click", ".rdbUser", function() {
//Check if this radio button is checked
if($(this).find("input[type=radio]").is(':checked'))
{
//Use .not() to exclude this
//Use .prop() to set checked to false
$(".rdbUser").not(this).find("input[type=radio]").prop("checked", false);
}
});
Use change event instead of click
IF using jquery version > 1.6 use prop else use attr
$(".rdbUser").change(function(){
if($(this).prop("checked")){
$("[id^='rdbUser']").not(this).prop("checked",false);
}
});
Hope this helps!. 'grdOrganization' is the Id of GridView.
<script type="text/javascript">
function ResetRadioBtns(rb) {
var gv = document.getElementById("<%=grdOrganization.ClientID%>");
var rbs = gv.getElementsByTagName("input");
var row = rb.parentNode.parentNode;
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
</script>
<asp:TemplateField ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:RadioButton ID="rbtnMaster" runat="server" onclick="ResetRadioBtns(this)" />
</ItemTemplate>
</asp:TemplateField>

Forcing button to cause postback

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

Categories