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;
}
Related
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.
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>
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
I have a simple question.
I have a FormView, with a save button. When the button is clicked, it saves to databse.
I've added an EXT message box to confirm if user wants to save the data or not. when he click yes on the messagebox yes button, then it should save the data.
I can't find where to write the yes button logic in the ext.
Here is my code :
<asp:FormView ID="myform" runat="server" DataSourceID="mydatasource" DefaultMode="Edit" DataKeyNames="Id" >
<EditItemTemplate>
<asp:TextBox ID="myText" runat="server" TextMode="MultiLine" ClientIDMode="Static"
Text='<%#Bind("xx") %>' />
<ext:Button ID="btn_Update" runat="server" AutoPostBack="false" CausesValidation="false" CommandName="Update" Text="Speichern" StyleSpec="float: left; margin-left:10px;"> <DirectEvents>
<Click OnEvent="btnUpdateClick"></Click>
</DirectEvents>
</ext:Button>
<script type="text/javascript">
function showResult(btn)
{
Ext.example.msg('Button Click', 'You clicked the {0} button', btn);
};
function showResultText(btn, text)
{
Ext.example.msg('Button Click', 'You clicked the {0} button and entered the text "{1}".', btn, text);
}
var showResult = function (btn) {
Ext.Msg.notify("Button Click", "You clicked the " + btn + " button");
};
var showResultText = function (btn, text) {
Ext.Msg.notify("Button Click", "You clicked the " + btn + 'button and entered the text "' + text + '".');
};
</script>
protected void btnUpdateClick(object sender, DirectEventArgs e)
{
X.Msg.Confirm("Confirm", "Are you sure you want to save?", new JFunction { Fn = "showResult" }).Show();
}
I guess you are looking for this: (Can be placed in any Demo-Box of the Sencha API)
Edit 2
I have totally overseen that you are using Direct. You should mention such things.
Is there any reason for using DirectEvent? I couldn't test it but how about this (the wrapping function may be unnecessary, but a normal ExtJS handler get button reference as first argument):
<form runat="server">
<ext:ResourceManager runat="server" />
<script runat="server">
[DirectMethod]
public void SetTimeStamp(string field)
{
// do your saving
}
</script>
<ext:TextField ID="TextField" runat="server" FieldLabel="Label"/>
<ext:Button ID="Button" runat="server" Text="Click Me" Icon="Lightning">
<Listeners>
<Click Handler="function() {Ext.Msg.show({title: 'Save?', msg: 'Do you want to save the data?:', buttons: Ext.Msg.YESNO,fn: function(btn){ if(btn == 'yes') {App.direct.SetTimeStamp(#{TextField}.getValue());}}})}" />
</Listeners>
</ext:Button>
</form>
Edit 1 Simply use Ext.Ajax.request()
Ext.Msg.show({
title: 'Save?',
msg: 'Do you want to save the data?:',
buttons: Ext.Msg.YESNO,
fn: function(btn, text){
Ext.Ajax.request({
url: 'yourUrl',
method: 'POST',
params: {
// your params
},
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});
}
});
Form example removed
Thank you all for your support, I found my way through your answers I will put it here maybe it can be useful for someone.
First, button code, need to have Isupload = "true"
ext:Button ID="btn_Update" runat="server" AutoPostBack="false" CausesValidation="false"
CommandName="Update" Text="Save" StyleSpec="float: left; margin-left: 10px;"
AutoScroll="False">
<DirectEvents>
<Click OnEvent="btnUpdateClick" IsUpload="true" AutoDataBind="true">
</Click>
</DirectEvents>
</ext:Button>
in the button event in the aspx :
protected void btnUpdateClick(object sender, DirectEventArgs e)
{
MessageBoxButtonConfig buttonYes = new MessageBoxButtonConfig();
buttonYes.Text = "Yes";
buttonYes.Handler = "Ext.net.DirectMethods.ClickedYES();";
MessageBoxButtonConfig buttonNo = new MessageBoxButtonConfig();
buttonNo.Text = "NO";
// buttonNo.Handler = "Ext.net.DirectMethods.ClickedNO();";
MessageBoxButtonsConfig yesNoButtons = new MessageBoxButtonsConfig();
yesNoButtons.Yes = buttonYes;
yesNoButtons.No = buttonNo;
X.Msg.Confirm("Save Changes", "Would you like to Save?", yesNoButtons).Show();
}
Last the Yes method that will save to database:
[DirectMethod]
public void ClickedYES()
{
Formview.UpdateItem(false);
Formview.DataBind();
}
I would suggest that instead of wiring the yes button of the dialog to perform the postback. You should wait for the message box to close and then invoke the postback functionality if the user clicked yes.
For example:
Ext.Msg.prompt('SaveChange', 'Would you like to save the changes?:', function(btn, text){
if (btn == 'yes'){
__doPostBack('btnSubmit','OnClick');
}
});
Replace btnSubmit with the name of your button.
Although the above solution would be my recommended approach, you could, alternatively, use jquery by doing:
$('btnSubmit').trigger('click');
Source: http://dev.sencha.com/playpen/docs/output/Ext.MessageBox.html
In my Asp project, I have a radio button inside my gridview. The radio button only allows user to select once every time.
However when user clicks a radio button, a confirm message will appear and the record will only be saved if the user clicks "OK".
Everything is working, but now I'm facing a problem. The radio button oncheckedchanged seems to not fire when user clicks "OK". How can I fire the radio button event once the user clicks "Ok"?
Here is my code:
Javascript
function RadioCheck(rb) {
var gv = document.getElementById('Content_PageContent_ucSubMenuItem_module_sales_customer_submenuitem_contactpersonlist_ascx_gvContactPersonList');var rbs = gv.getElementsByTagName("input");
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
//if radio button is check but not the selected value then false
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
return confirm('Confirm Save?');
}
client-side
<asp:TemplateField HeaderText="Default" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:RadioButton ID="rdbtnDefault" runat="server" onclick="RadioCheck(this);" oncheckedchanged="rdbtnDefault_CheckedChanged" Visible='<%#((string)Eval("DEFAULT")) == "Y" ? false : true %>'/>
<asp:Image ID="imgDefault" runat="server" Height="13px" ImageUrl="~/Styles/images/tick-48x48.png" Width="13px" Visible='<% ((string)Eval("DEFAULT")) == "Y" ? true : false %>' />
</ItemTemplate>
Server side
//--Register for in post back--
if (Page.ClientScript.IsClientScriptBlockRegistered(DataUCContactListing) == false) {
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "gvRdBtnSelectOnce", blcGenerateScript.gvRdBtnSelectOnce(gvContactPersonList.ClientID,true), true);
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "gvSelectAllChkBox", blcGenerateScript.gvSelectAllChkBox(gvContactPersonList.ClientID), true);
}
//**Register for script**
protected void rdbtnDefault_CheckedChanged(object sender, EventArgs e) {
try {
RadioButton lnBTNDone = (RadioButton)sender;
GridViewRow row = (GridViewRow)lnBTNDone.NamingContainer;
string accountID = gvContactPersonList.DataKeys[row.RowIndex].Values[0].ToString();
int contactID = int.Parse(gvContactPersonList.DataKeys[row.RowIndex].Values[1].ToString());
using (TransactionScope scope = new TransactionScope()) {
dlcCustomerDB.updateAccountOtherDefaultN(accountID);
dlcCustomerDB.updateAccountDefaultY(accountID, contactID);
scope.Complete();
}
createGridView();
this.Session[gbcMessageSessionID.message1] = gbcMessageAlert.saveSuccessfully;
Response.Redirect(Request.Url.ToString());
} catch (Exception ex) {
logger.Error(ex.Message);
throw;
}
}
Look into following URLs
http://www.asp.net/web-forms/tutorials/data-access/enhancing-the-gridview/adding-a-gridview-column-of-radio-buttons-vb
Radiobutton checked change event not firing in gridview
Please look into this code
<asp:RadioButton ID="rdbtnDefault" runat="server" onclick="return RadioCheck(this);" oncheckedchanged="rdbtnDefault_CheckedChanged" Visible='<%#((string)Eval("DEFAULT")) == "Y" ? false : true %>' AutoPostBack="True" />
I have added "return" keyword for onclick event of RadioButton.