I am working on an asp.net application and I have a delete image button like this:
<asp:GridView ID="grdPaymethods" runat="server" ShowHeader="False" GridLines="None" AutoGenerateColumns="False" OnRowDataBound="grdPaymethods_RowDataBound" OnRowDeleting="grdPaymethods_RowDeleting">
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<Columns>
<asp:ImageButton ID="IBtnDelete" runat="server" ToolTip="Click to delete"
CommandArgument='<%# Eval("MethodId") %>'
OnClientClick="javascript:return deleteItem(this.name, this.alt);"
ImageUrl="~/Images/Delete.png" AlternateText='<%# Eval("MethodId") %>'
CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
and I see that row deleting event is fired. but I want to use linkbutton instead of image button. So I used this code:
<asp:LinkButton ID="IBtnDelete1" runat="server" ToolTip="Click to delete"
CommandArgument='<%# Eval("MethodId") %>'
OnClientClick="javascript:return deleteItem(this.name, this.alt);"
Text="Delete" AlternateText='<%# Eval("MethodId") %>'
CommandName="Delete"></asp:LinkButton>
It shows link button, but clicking link button just refreshes page and doesnt call row deleting event. I tried OnRowCommand="grdPaymethods_RowCommand" event and linkbutton on click events as well but they are not fired and page just refreshed.
here are js functions:
function deleteItem(uniqueID, itemID) {
e.preventDefault();
var dialogTitle = 'Permanently Delete Item ' + itemID + '?';
$("#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(uniqueID, '');
$(this).dialog("close");
},
"Cancel": function () { $(this).dialog("close"); }
}
});
$('#deleteConfirmationDialog').dialog('open');
return false;
}
$(function () {
InitializeDeleteConfirmation();
});
function InitializeDeleteConfirmation() {
$('#deleteConfirmationDialog').dialog({
autoOpen: false,
resizable: false,
height: 140,
modal: true,
buttons: {
"Delete": function () {
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
}
and row deleting event:
protected void grdPaymethods_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// cancel the automatic delete action
e.Cancel = true;
// do the delete
// _categoryResposite.DeleteCategories(Convert.ToInt32(e.id));
grdPaymethods.DataSource = customer.PaymentMethods.OrderByDescending(a => a.Preferred);
grdPaymethods.DataBind();
}
Please suggest solution to it.
Related
I have a jquery-ui modal dialog on my page which I show when a user clicks a Decline button on a control which is contained within an asp.net UpdatePanel, there are many of these controls on the page.
Script:
function confirmDecline(event) {
event.preventDefault();
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Confirm": function () {
$('form').submit();
return true;
},
Cancel: function () {
$(this).dialog("close");
}
}
});
}
Pod markup:
<div class="dms-pod">
<ul>
<li><strong><asp:Literal ID="litCompanyName" runat="server" /></strong></li>
<li><asp:Literal ID="litVatNumber" runat="server" /></li>
<li><asp:Literal ID="litTown" runat="server" /></li>
</ul>
<asp:Panel ID="pnlDmsForm" runat="server" CssClass="dms-form" DefaultButton="btnAccept">
<asp:TextBox ID="txtDmsNumber" runat="server" placeholder="DMS number" />
<asp:RequiredFieldValidator ID="reqDmsNumber" runat="server" ErrorMessage="Invalid DMS number" Display="Dynamic" CssClass="error" ControlToValidate="txtDmsNumber" />
<ajaxToolkit:ValidatorCalloutExtender ID="valDmsNumber" runat="server" TargetControlID="reqDmsNumber" HighlightCssClass="error" />
<div class="dms-buttons">
<div class="container">
<asp:LinkButton ID="btnAccept" runat="server" CssClass="btn" Text="accept" OnClick="btnAccept_Click" />
</div>
<div class="container">
<asp:LinkButton ID="btnDecline" runat="server" CssClass="btn-alt" Text="decline" OnClick="btnDecline_Click" OnClientClick="confirmDecline(event)" />
</div>
</div>
<div class="clear"></div>
</asp:Panel>
<div class="clear"></div>
<asp:HiddenField ID="hdnDealershipIRLinkID" runat="server" />
Which is then contained inside an update panel:
<asp:UpdatePanel ID="updPendingDms" UpdateMode="Always" runat="server">
<ContentTemplate>
<asp:Repeater ID="rptPendingDmsRequests" runat="server" OnItemDataBound="rptPendingDmsRequests_ItemDataBound" OnItemCreated="rptPendingDmsRequests_ItemCreated">
<ItemTemplate>
<uc:DmsRegisterPod runat="server" ID="ucDmsRegisterPod" />
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
I'm using event.preventDefault() to stop the button action from firing, however, I'd also like to allow the action to continue if the user clicks the Confirm button. I had assumed I could just use:
$('form').submit();
In the dialog Confirm function, but this fires the validators of the other controls in the repeater/update panel. Is there a way to achieve this?
Managed to solve this, posting the answer in case it helps anyone else facing a similar problem.
I pass in the id of the control which triggered the click:
OnClientClick="confirmDecline(event, this.id)"
I then fire off __doPostBack with this id in the dialog Confirm function:
function confirmDecline(event, controlId) {
event.preventDefault();
controlId = controlId.replace(/_/g, '$');
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Confirm": function () {
$(this).dialog("close");
__doPostBack(controlId, '');
return true;
},
Cancel: function () {
$(this).dialog("close");
}
}
});
}
Hi Please check i want to get click event in code behind as i am using master page concept and i have one child form of it in this page i have ContentPlaceHolder, My button "btnSubmit" this is a linkbutton which is under GridView. i want loading image when i will click on btnSubmit button. please check and help.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
function ShowProgress() {
setTimeout(function () {
var modal = $('<div />');
modal.addClass("modal");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
}, 200);
}
$('form').live("submit", function () {
ShowProgress();
});
aspx page..
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Journal" HeaderText="Customer Id" />
<asp:BoundField DataField="ISBN" HeaderText="Contact Name" />
<asp:BoundField DataField="Status" HeaderText="City" />
<asp:TemplateField HeaderText="Btn">
<ItemTemplate>
<asp:Button ID="btnSubmit" runat="server" Text="Load Customers"
OnClick="btnSubmit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div class="loading" align="center">
Downloading Files. Please wait<br />
<br />
<img src="loader.gif" alt="" />
</div>
</asp:Content>
In cs Page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string script = "$(document).ready(function () { $('[id*=btnSubmit]').click(); });";
ClientScript.RegisterStartupScript(this.GetType(), "load", script, true);
}
}
try this way
Script AS
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function ShowProgress() {
setTimeout(function () {
var modal = $('<div />');
modal.addClass("modal");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
}, 200);
}
$('form').live("submit", function () {
ShowProgress();
});
</script>
And Add event onrowdatabound in grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
And CS page
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Button btnSubmit = e.Row.FindControl("btnSubmit") as Button;
btnSubmit.Attributes.Add("OnClick", "ShowProgress();");
}
}
Use OnClientClick event of the button also in this event call a javascript function which change the css of the progress bar to visible.
OnClientClick="ShowProgress();return true;"
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 server 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>
The server side code is below:
protected void ddlTransactionList_SelectedIndexChanged(object sender,
EventArgs e)
{
//Your Code
if (OnDataChanged != null)
OnDataChanged(sender, e);
}
Check the generated HTML code of your page and have a closer look on your dropdown. It should look like this:
<select name="gridView$ctl02$ddlTransactionList" onchange="return PopupDialog('Remittance Confirmation','Are you sure you want to update the status?.');setTimeout('__doPostBack(\'gridView$ctl02$ddlTransactionList\',\'\')', 0)" id="gridView_ddlTransactionList_0">
The problem is that you "return" the outcome of your PopupDialog so that the __doPostback function (AutoPostBack) has no chance of getting called. My advice: Only return if the user rejects the change. If the user agrees dont return anything.
Edit (forgot post the solution code)
<asp:DropDownList ID="ddlTransactionList" AutoPostBack="True" OnSelectedIndexChanged="ddlTransactionList_SelectedIndexChanged" onchange="if(! PopupDialog('Remittance Confirmation','Are you sure you want to update the status?.')){return false;}" runat="server"></asp:DropDownList>
I'm trying to make a jQuery confirm dialog call a web method. The dialog is called when the delete button in a GridView in an UpdatePanel is clicked.
However, when I click on the button, an error "Invalid postback or callback argument." I searched through some of the questions/answers here and tried overriding the Render event to register the UpdatePanel.
Here's my aspx page:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DoPostBack._Default" %>
<asp:Content ID="conStyles" runat="server" ContentPlaceHolderID="cphStyles">
</asp:Content>
<asp:Content ID="conMain" runat="server" ContentPlaceHolderID="cphMain">
<asp:UpdatePanel ID="upMovies" runat="server" UpdateMode="Conditional" onload="upMovies_Load">
<ContentTemplate>
<asp:GridView ID="gvItems" runat="server" CssClass="tbl-movies" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" HeaderStyle-CssClass="col-title-header" ItemStyle-CssClass="col-title"/>
<asp:BoundField DataField="Director" HeaderText="Director" HeaderStyle-CssClass="col-director-header" ItemStyle-CssClass="col-director" />
<asp:BoundField DataField="Year" HeaderText="Year" HeaderStyle-CssClass="col-year-header" ItemStyle-CssClass="col-year" />
<asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="table-actions">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" ImageUrl="Images/edit.png" runat="server"
Text="Edit" UseSubmitBehavior="False" />
<asp:ImageButton ID="btnDelete" ImageUrl="Images/delete.png" runat="server"
Text="Delete" UseSubmitBehavior="False" CssClass="btn-delete-movie" />
<asp:HiddenField ID="hfMovieId" runat="server" Value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div id="confirmDelete" class="popup popup-confirm">
<div class="popup-title">
<h4>Delete Movie</h4>
</div>
<div class="popup-content">
<div class="confirm-message">
</div>
<div class="buttons center">
<input id="btnDeleteConfirm" type="button" value="OK" class="button btn-confirm" />
<input id="btnDeleteCancel" type="button" value="Cancel" class="button btn-delete-cancel btn-close-popup" />
</div>
</div>
</div>
</asp:Content>
<asp:Content ID="conScripts" runat="server" ContentPlaceHolderID="cphScripts">
<script src="Scripts/site.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var btnDelete = $('.btn-delete-movie');
btnDelete.on('click', function (e) {
e.preventDefault();
var row = $(this).closest('tr'),
title = row.find('.col-title').text(),
movieId = parseInt(row.find('input[type=hidden]').val());
showConfirmPopUp('confirmDelete',
'Are you sure you want to delete the movie "' + title + '"?',
function () { deleteMovie(movieId); }, //call the DeleteMovie web method
function () { }); //do nothing else
});
});
function deleteMovie(id) {
$.ajax({
type: 'POST',
contentType: 'application/json',
data: '{"id":' + id + '}',
url: 'Default.aspx/DeleteMovie',
dataType: 'json',
success: function (data) {
__doPostBack('<%= upMovies.ClientID %>', '');
closePopUp('confirmDelete');
},
error: function (jqXHR, textStatus, errorThrown) {
showError(jqXHR, textStatus, errorThrown);
}
});
}
</script>
</asp:Content>
Code-behind:
public partial class _Default : System.Web.UI.Page
{
#region Events
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateMovies();
}
}
protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(upMovies.UniqueID);
foreach (GridViewRow row in gvItems.Rows)
{
var btnDelete = row.FindControl("btnDelete");
var btnEdit = row.FindControl("btnEdit");
ClientScript.RegisterForEventValidation(btnDelete.UniqueID);
ClientScript.RegisterForEventValidation(btnEdit.UniqueID);
}
base.Render(writer);
}
protected void upMovies_Load(object sender, EventArgs e)
{
PopulateMovies();
}
#endregion
#region Private Methods
private void PopulateMovies()
{
var data = from m in Movie.GetAll()
orderby m.Year descending, m.Title ascending
select m;
gvItems.DataSource = data;
gvItems.DataBind();
}
#endregion
#region Web Methods
[WebMethod]
public static object DeleteMovie(int id)
{
Movie.Delete(id);
return UpdateItems();
}
#endregion
}
I'm using the jQuery approach because I don't want to use the ModalPopupExtender. I don't want to set EnableEventValidation to false either.
Also, why is the upMovies_Load called when I click on the delete button? Shouldn't it only be called when the ok button of the confirm dialog is clicked?
I'm kind of a beginner, help would be greatly appreciated.
Thank you :)
Okay, you have to rebind the JavaScript again via
Sys.WebForms.PageRequestManager.GetInstance().add_endRequest(function(){
//$(document).ready() code here
});
I'm working on a context menu for items in my GridView, but there's one major snag. I can't seem to figure out how to send the PK value for the row that is right-clicked on to the JQuery that interacts with my HTTP Handler to update the database.
Basically, the context menu will have 3 items, Reply, Mark as Read, and Delete.
In each case I need the mailid value from the database to be available to the JQuery so that I can redirec the user to a page where they can reply to the selected mail or to tell the HTTP Handler which item in the database it's supposed to update.
Here's my code:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "getMailDetail(" + DataBinder.Eval(e.Row.DataItem, "mailid") + ")";
e.Row.Attributes["id"] = DataBinder.Eval(e.Row.DataItem, "mailid");
Label lblStatus = (Label)e.Row.FindControl("lblStatus");
if (lblStatus.Text == "unread")
{
e.Row.Font.Bold = true;
}
}
}
I'm setting the onClick attribute for the Rows so that clicking anywhere on the GridViewRow will trigger the page to display the mail in detail. I figured I could get the mailid value in the same way using a different attribute.
And on the .aspx...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.contextMenu.js"></script>
<script type="text/javascript">
function getMailDetail(mailId) {
$.ajax({
type: "GET",
url: '<%= ResolveUrl("~/GetMail.ashx") %>',
data: { mid: mailId },
success: function (data) {
var pnlList = $('#<%= pnlList.ClientID %>');
var pnlMail = $('#<%= pnlMail.ClientID %>');
var lblFrom = $('#<%= lblFrom.ClientID %>');
var lblDate = $('#<%= lblDate.ClientID %>');
var lblSubject = $('#<%= lblSubject.ClientID %>');
var lblMessage = $('#<%= lblMessage.ClientID %>');
lblFrom.text(data.From);
lblDate.text(data.Date);
lblSubject.text(data.Subject);
lblMessage.text(data.Message);
pnlList.css("display", "none");
pnlMail.css("display", "block");
}
});
}
function markRead(mailId) {
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/MailAction.ashx") %>',
data: { mid: mailId, act: "markRead" },
success: window.location = "Inbox.aspx"
});
}
function deleteMail(mailId) {
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/MailAction.ashx") %>',
data: { mid: mailId, act: "Delete" },
success: window.location = "Inbox.aspx"
});
}
</script>
<div class="columns">
<div class="leftcol">
Compose Message
<ul>
<li>Sent Items</li>
<li class="active">Inbox</li>
<li>Deleted Items</li>
</ul>
</div>
<div class="rightcol">
<asp:Panel runat="server" ID="pnlList">
<div class="rightalign">
<asp:Label runat="server" ID="lblCount"></asp:Label>
</div>
<asp:GridView runat="server" ID="gvItems" DataKeyNames="mailid"
AutoGenerateColumns="false" onrowdatabound="gvItems_RowDataBound"
Width="100%">
<Columns>
<asp:TemplateField ItemStyle-CssClass="centeralign">
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkSelectAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="hidden" HeaderStyle-CssClass="hidden">
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Text='<%# DataBinder.Eval(Container.DataItem, "status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-CssClass="hidden" HeaderStyle-CssClass="hidden" DataField="mailid" />
<asp:BoundField DataField="firstname" HeaderText="From" SortExpression="firstname" />
<asp:BoundField DataField="datesent" HeaderText="Date" SortExpression="datesent" DataFormatString="{0:yyyy/MM/dd HH:mm}" />
<asp:BoundField DataField="subject" HeaderText="Subject" SortExpression="subject" />
</Columns>
</asp:GridView>
</asp:Panel>
<asp:Panel runat="server" ID="pnlMail" cssclass="hidden">
<p>From: <asp:Label runat="server" ID="lblFrom"></asp:Label><br />
Sent On: <asp:Label runat="server" ID="lblDate"></asp:Label><br />
Subject: <asp:Label runat="server" ID="lblSubject"></asp:Label></p>
<p><asp:Label runat="server" ID="lblMessage"></asp:Label></p>
</asp:Panel>
</div>
</div>
<!-- Row Context Menu -->
<ul id="contextmenu" class="contextMenu">
<li>Reply</li>
<li>Mark As Read</li>
<li>Delete</li>
</ul>
<script type="text/javascript">
$(document.ready(function() {
$(".dataRow").contextMenu({
menu: 'contextmenu' },
function(action, el, pos, mid) {
contextMenuWork(action, el, pos);
}
);
},
function contextMenuWork(action, el, pos) {
var mid = $(el).attr("id");
switch (action) {
case "reply":
{
window.location = "Reply.aspx?id=" + mid;
break;
}
case "mread":
{
markRead(mid);
break;
}
case "delete":
{
deleteMail(mid);
break;
}
}
}
);
</script>
Unfortunately there seems to be a problem in my approach here as I'm getting an InvalidCastException on the assignment of the id attribute on the newly bound GridViewRow:
Cannot implicitely convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
So, I replace that line with this
e.Row.Attributes["id"] = (string)DataBinder.Eval(e.Row.DataItem, "mailid");
And now, although there are no errors that Visual Studio can tell me about at design time, at runtime, I get the following InvalidCastException:
Unable to cast object of type 'System.Int32' to type 'System.String'.
I have no idea where the integer is coming from here so I don't know how to proceed.
Any help will be greatly appreciated.
I never seemed able to get a working cast on the value here, so what I did was to change the RowDataBound void to the following:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var mailid = DataBinder.Eval(e.Row.DataItem, "mailid");
e.Row.Attributes["onClick"] = "getMailDetail(" + DataBinder.Eval(e.Row.DataItem, "mailid") + ")";
e.Row.Attributes["id"] = mailid.ToString();
Label lblStatus = (Label)e.Row.FindControl("lblStatus");
if (lblStatus.Text == "unread")
{
e.Row.Font.Bold = true;
}
}
}
Declaring a new var and with the DataItem value for "mailid" and then giving it a .ToString() fixed all my problems