Call jquery modal popup from asp.net dropdownlist change - c#

I have a requirement to do some logic execution upon change of dropdownlist value. Before executing the logic i need to take user confirmation and then call service side method to complete the process. Not sure How to call server side method based on modal popup confirmation response from user. So if user confirms with Yes button on the modal popup server side code should be called otherwise do nothing.
Here is the code i have . Server side does not get called upon modal popup confirmation.
function PopupDialog(title, text) {
var div = $('<div>').html('<br>'+text).dialog({
title: title,
modal: true,
height: 190,
width: 320,
buttons: {
"Yes": function () {
$(this).dialog('close');
},
"No": function () {
$(this).dialog('close');
}
}
});
return true;
};
<asp:GridView runat="server" ID="grdTransactions" SkinID="gridviewskin"
AllowSorting="true" AllowPaging="true" PageSize="30" Width="100%"
OnRowDataBound="grdTransactions_RowDataBound"
OnDataBound="grdTransactions_DataBound"
OnSelectedIndexChanged="grdTransactions_SelectedIndexChanged">
.............
<asp:TemplateField Visible="true" HeaderText="Status" >
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Visible="False" Text='<%# ShowStatus( Container.DataItem ) %>' />
<asp:DropDownList ID="ddlTransactionList" AutoPostBack="True" OnSelectedIndexChanged="ddlTransactionList_SelectedIndexChanged" onchange="return PopupDialog('Remittance Confirmation','Are you sure you want to update the status?.');" runat="server"></asp:DropDownList>
<br/>
</ItemTemplate>
</asp:TemplateField>
**Server Side Code --**
protected void ddlTransactionList_SelectedIndexChanged(object sender,
EventArgs e)
{
//Your Code
if (OnDataChanged != null)
OnDataChanged(sender, e);
}
Thank you

I think there is a conflict between the javascript created by ASP.NET and the onchange event you are adding to the dropdown (onchange="return .... ") so it is ignoring the the call that posts back.
I would start by trying something like this on the front end:
// remove the autopostback & onchange from the ddl definition
<asp:DropDownList ID="ddlTransactionList" runat="server"></asp:DropDownList>
function PopupDialog(title, text) {
var div = $('<div>').html('<br>'+text).dialog({
title: title,
modal: true,
height: 190,
width: 320,
buttons: {
"Yes": function () {
$(this).dialog('close');
return true;
},
"No": function () {
$(this).dialog('close');
}
}
});
};
$(document).ready(function(){
$("<% ddlTransactionList.CLientID %>").change(function(){
if(PopupDialog('Remittance Confirmation','Are you sure you want to update the status?.')){
__doPostBack('ddlTransactionList')
}
});
});
In the code-behind:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"]; // parameter
// Request["__EVENTTARGET"]; // ddlTransactionList
// make your call to ddlTransactionList_SelectedIndexChanged() here
}
Let us know if this helps.

Related

Call jQuery function from Gridview link button

In my application I have a jQuery function, and I want to call this function from a gridview link button. I tried this code shown here, but the function is not called:
<script type="text/javascript">
$(function () {
var JavascriptBlah = '<%=msUntilFour%>'
var fileName = '<%=msUntilFour%>';
$('input[id$="lnkCustomer"]').click(function () {
$("#dialog").dialog({
modal: true,
title: fileName,
width: 600,
height: 600,
buttons: {
Close: function () {
$(this).dialog('close');
}
},
open: function () {
var object = "<object data=\"{FileName}\" type=\"application/pdf\" width=\"700px\" height=\"700px\">";
object += "If you are unable to view file, you can download from here";
object += "</object>";
object = object.replace(/{FileName}/g, "Doc/Demo.pdf");
$("#dialog").html(object);
}
});
});
});
</script>
Aspx markup:
<asp:GridView ID="gridView1" runat="server" CssClass="mydatagrid"
HeaderStyle-CssClass="header" RowStyle-CssClass="rows"
AutoGenerateColumns="false"
PageSize="10" EmptyDataText="No Records Available">
<HeaderStyle CssClass="header"></HeaderStyle>
<PagerStyle ForeColor="Red" HorizontalAlign="Center"></PagerStyle>
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="CustomerID">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkCustomer" Text='<%#Eval("Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle CssClass="rows"></RowStyle>
</asp:GridView>
</div>
<div id="dialog" style="display: none">
How can I call the jQuery function from the gridview link button?
Thanks in advance.
Don't call function by its id as it generate multiple ids for each row.
You can achieve this by javascript simply attach a client side event onclick='myTestFun();' to LinkButton.
First you can declare function in script section and then add in OnClientClick property of LinkButton.
ASPX Code
<asp:LinkButton runat="server" ID="lnkCustomer" Text='<%#Eval("Name") %>'
OnClientClick="OpenModel();" > </asp:LinkButton>
JS Code
$(document).ready(function(){
OpenModel();
});
function OpenModel() {
$("#dialog").dialog({
modal: true,
title: fileName,
width: 600,
height: 600,
buttons: {
Close: function () {
$(this).dialog('close');
}
},
open: function () {
var object = "<object data=\"{FileName}\" type=\"application/pdf\" width=\"700px\" height=\"700px\">";
object += "If you are unable to view file, you can download from here";
object += "</object>";
object = object.replace(/{FileName}/g, "Doc/Demo.pdf");
$("#dialog").html(object);
}
});
});

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

Get multiline textbox value from jquery dialog

I try to make a popup dialog in my asp net website with form for send message.
I do in asp net user control:
<asp:Panel runat="server" ID="panelMain" ToolTip="" style="display: none">
<asp:Label runat="server" ID="Label1" AssociatedControlID="txtMessage" Text=""></asp:Label>:
<br />
<asp:TextBox runat="server" ID="txtMessage" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1"
ControlToValidate="txtMessage" Display="Dynamic"
ErrorMessage=""></asp:RequiredFieldValidator>
<br />
<asp:Button ID="butOk" runat="server" Text="" OnClick="butOk_Click"/>
<asp:Button ID="butCancel" runat="server" Text="" CausesValidation="false" />
</asp:Panel>
<script type="text/javascript">
$(document).ready(function()
{
$(".lbPopupLink").click(function() { //click hyperlink form main page
$("#<%= this.panelMain.ClientID %>").css("display", "block");
$("#<%= this.panelMain.ClientID %>").dialog
({
autoOpen: false,
modal: true,
width: 400,
height: 300,
dialogClass: "popupDialog",
resizable: false,
overlay: { opacity: 0.5, background: "black" },
}).dialog("open");
return false;
});
$("#<%= this.butCancel.ClientID %>").click(function()
{
$("#<%= this.panelMain.ClientID %>").dialog("close");
return false;
});
$("#<%= this.butOk.ClientID %>").click(function()
{
return $("#<%= this.panelMain.ClientID %>").dialogCloseAndSubmit($(this).attr("id"));
});
});
</script>
$.fn.extend({
dialogCloseAndSubmit: function(butOkId)
{
var dlg = $(this).clone();
$(this).dialog("destroy").remove();
dlg.css("display", "none");
$("form:first").append(dlg);
$("#" + butOkId, dlg).click();
return true;
}
});
In code behind:
protected void butOk_Click(object sender, EventArgs e)
{
// will be send mail
Literal str_message = new Literal();
str_message.Mode = LiteralMode.PassThrough;
str_message.Text = "<br />Success!Message: " + this.txtMessage.Text;
this.Page.Controls.Add(str_message);
}
And it's all good when TextBox is one line (Success!Message: hello), but if I change attribute to TextMode="MultiLine" I have no TextBox value (Success!Message:)
How can I solve this problem?
Maybe Try:
$(this).find('textarea[id*=txtMessage]').val();
As discussed in this answer

extjs/c# Yes saves to the database

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

How to call server side code from javascript in asp.net?

I have Repeater control like this;
<asp:Repeater ID="repeaterCategoryList" runat="server"
onitemcommand="repeaterCategoryList_ItemCommand">
<ItemTemplate>
<td class="center">
<asp:Button ID="buttonDelete" runat="server" CssClass="btn btn-primary" CommandName="Delete" Text="Delete"
CommandArgument='<%# Eval("CategoryId") %>'/>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
And my code behind page looks like this;
protected void repeaterCategoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//my server side logic here
}
}
And my javascript code in .aspx file looks like this:
<script>
$(function () {
$('#buttonDelete').live('click', function (e) {
e.preventDefault();
$.alert({
type: 'confirm'
, title: 'Alert'
, text: '<p>Are you sure, you want to delete this category</p>'
, callback: function () {
// call server side here
}
});
});
});
</script>
How do I call the repeater delete command logic inside my javascrpt?
Is there any alternative way to do this?
You can use ItemDatabound property of repeater to bind the Javascript function to Dalete Button Onclick event as follow...
CodeBehind:-
void Repeater1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
int IdToBeDeleted=((Label)e.Item.FindControl("idFieldControl")).Text;
Button Btn= (Button)e.Item.FindControl("buttonDelete");
Btn.Attributes.Add("onclick","return ConfirmDelete('"+IdToBeDeleted+"')");
}
}
Javascript:
<script>
function ConfirmDelete(var idVal)
{
if(Confirm("Are you sure, you want to delete this category?"))
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","DeletePage.aspx?id="+idVal,true);
xmlhttp.Send();
}
}
</script>
DeletePage.aspx:
function pageLoad(sender, eventArgs)
{
if(!IsPostBack)
{
int IdToBeDeleted=Request.QueryString["id"];
Write Your Delete Code Here...
if delete successful...Response.Write("Delete Successful");
}
}
Use OnClientClick in the button click
and write the function name in it. when the function returns false, then the server side method is not called. If the JS Function returns true, then the server side method is executed
<asp:Button ID="buttonDelete" runat="server" CssClass="btn btn-primary" CommandName="Delete" Text="Delete" onclick="Button_Click_Event" OnClientClick="return Javascript_Function()" CommandArgument='<%# Eval("CategoryId") %>'/>
OnClientClick, is the only way to get between a button and its post back.

Categories