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;"
Related
In my page when it's creating, everything is working fine but when I am clicking on the button to show the selected row, then my grid view is not rendering as a datatable. What I need to do to fix this or what I am doing wrong?
My script:
<script type="text/javascript">
$(function () {
$('[id*=gvTest]').prepend($("<thead></thead>").append($(this).find("tr:first"))).DataTable({
"responsive": true,
"sPaginationType": "full_numbers",
});
});
$(document).ready(function () {
var table = $('#gvTest').DataTable();
$('#gvTest tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#btnRead').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
});
} );
</script>
My Grid:
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="PatientID" HeaderText="Patient ID" >
</asp:BoundField>
<asp:BoundField DataField="PatientName" HeaderText="PatientName" >
</asp:BoundField>
<asp:BoundField DataField="Age" HeaderText="Age" >
</asp:BoundField>
<asp:BoundField HeaderText="Sex" DataField="Sex" >
</asp:BoundField>
<asp:BoundField HeaderText="Mod" DataField="Modality" >
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
When my page is created:
Everything is working fine, but when I click a button then this happens:
What do I need to do now to fix this problem ?
The UpdatePanel refreshes the DOM, so any changes made to it with jQuery are lost. You need to call DataTable() again after an Async PostBack. You can use the PageRequestManager for that.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
createDataTable();
});
createDataTable();
function createDataTable() {
var table = $('#gvTest').DataTable();
$('#gvTest tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
}
</script>
The best way to fix this issue is by implementing this in pageLoad function.
In this case I used a Gridview:
function pageLoad() {
$("<thead></thead>").append($("#grvPast tr:first")).prependTo($("#grvPast"));
$('#grvPast').dataTable();
}
after using a lots of others code i did'nt get a proper solution so i used this on my page load and its working fine
gvTest.UseAccessibleHeader = true;
//adds <thead> and <tbody> elements
gvTest.HeaderRow.TableSection =
TableRowSection.TableHeader;
I have gridview showing columns BusRoute,BusNo and Action.Where action contains the linkbuttons to display another gridview.I want to display it in jquery dialog.My codes are.
ASPX Code:
First Gridview:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClientClick="showDialog();">Shipment Status</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
Second Gridview:
<div class="gridview_stop" id="popup">
<asp:GridView ID="Stops" runat="server" AutoGenerateColumns="False" CellPadding="6" Width="190px">
<Columns>
<asp:BoundField HeaderText="Bus Stop" DataField="StopName" HeaderStyle-BackColor="#006B89">
<HeaderStyle BackColor="#006B89" Font-Size="18px" Font-Bold="false"></HeaderStyle>
<ItemStyle BackColor="#E0E0E0" HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
Code Behind File:
protected void search_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("spGetRoutes", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BusStop1", Source.Text);
cmd.Parameters.AddWithValue("#BusStop2", Destination.Text);
adapter.SelectCommand = cmd;
adapter.Fill(ds);
adapter.Dispose();
cmd.Dispose();
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
Route.DataSource = ds.Tables[0];
Route.DataBind();
Stops.DataSource = null;
Stops.DataBind();
Lblmsg.Text = "";
}
else
Lblmsg.Text = "No Direct Bus Between These Stop";
Lblmsg.ForeColor = Color.WhiteSmoke;
Route.Dispose();
Route.DataBind();
Stops.Dispose();
Stops.DataBind();
}
protected void Route_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click last column for selecting this row.";
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string Name = Route.SelectedRow.Cells[0].Text;
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataSet ds1 = new DataSet();
string connetionString = "Data Source=.;Initial Catalog=BusService;uid=sa;Password=Murli#925";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand cmd = new SqlCommand("spGetStops", connection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
int BusNo= Convert.ToInt32(Name);
cmd.Parameters.AddWithValue("#BusNo",BusNo);
adapter1.SelectCommand = cmd;
adapter1.Fill(ds1);
adapter1.Dispose();
cmd.Dispose();
connection.Close();
Stops.DataSource = ds1.Tables[0];
Stops.DataBind();
}
Jquery Function:
<script type="text/javascript">
$("#lnkbtn").live("click",
function showDialog() {
$("#popup").dialog({
show: { effect: "fold", duration: 4000 },
hide: { effect: "fold", duration: 4000 },
});
return false;
});
$(document).click(function (event) {
if (!$(event.target).closest('#popup').length) {
if ($('#popup').is(":visible")) {
$('#popup').dialog('close');
}
}
})
</script>
Thanks & Regards.
Take a look at your rendered html when you run the page. Unless you set ClientIDMode to Static I doubt that your button ID's are $("#lnkbtn") but more like $("#gvWhatever_lnkbtn_0")
Set OnClientClick="showDialog();" or $("#lnkbtn").live("click", function showDialog(){...}) no need to do both.
Using a Server Control button to activate a popup usually doesn't work. Especially if GridView Row Selection is enabled. I can't tell if your first GridView has that feature enabled as I only see a portion of the listing. But what tends to happen is you trigger a postback while trying to display the popup so you never see the popup.
Also your second popup contains a gridview, which requires a databind. so you need to make sure the gridview is populated with the data before activating the popup
Two methods for showing a popup using jquery from within a Gridview:
A portion of a GridView markup with 2 TemplateField's
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
<div>
<div class="rs-icon rs-icon-info tooltip-marker" role="button">
</div>
<div id="ContactInfo" style="display:none;">
<table id="tblContactDetail" class="ContactDetail Note">
<tr>
<td style="width: 80px">Name</td>
<td style="width: 100%">
<asp:Literal ID="Literal1" runat="server"
Text='<%# Eval("expert_name") %>' />
</td>
</tr>
.
.
.
</table>
</div>
</div>
<ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CV">
<ItemTemplate>
<div id="divButtonViewCV" runat="server"
class="rs-icon rs-icon-cv" role="button"
onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>' >
</div>
</ItemTemplate>
</asp:TemplateField>
In the above markup I'm setting up for two styles of "popup". The first Template uses jQueryUI ToolTip widget which is activated on mouseover/out. This is nice because it doesn't require a click which means no worries about a postback mucking up the works. The interesting thing here is that I'm using a div as button.
How it works: The div with the .tooptip-marker class is set up to activate a jqueryui tooltip which will display the contents of <div id="ContentInfo"> by grabbing the inner html of the sibling div of the activating button. Note that this div is styled as display:none; so that the content is available for the tooltip but hidden so the main GridView displays as normal.
For brevity, I included only a portion of the content of <div id="ContentInfo">. But It can contain anything really. In my code it's a simple <table> containing contact information fields (using bound <asp:Literal> controls) that are part of the primary GridView data source.
But this could just have easily been an embedded GridView with it's own data source that is bound in the OnRowDatabound event of the primary GridView.
The following jquery sets up the widget. See jQueryUI ToolTip widget for more complete documentation
$( function() {
$( document ).tooltip( {
items: ".tooltip-marker",
content: function() {
return $( this ).next().html();
},
position: {
my: "left top",
at: "right+5 top-5"
}
} )
} );
The second Template field is used to activate a popup. This is where you have to be careful about postbacks. Again I use a <div> styled as an icon and treated as a simple button because I've added onclick.
Clicking this button displays a popup so you can view a persons CV in PDF format. The PDF is stored in our database as a varbinary. Here I use another jquery addon, (colorbox), to display the PDF as a popup over the page.
In the ViewPDF() function below note that we prevent the "bubbling up" of the click event to the GridView by setting cancelBubble = true (for older IE) or a call to stopPropagation() (all other browsers).
In this code, colorbox sets up an iframe and passes the href parameter to its src attribute. I'm making a call to an .ashx page which is an asp Generic Handler which allows us to serve up other type of content without standard web page overhead. This could just as easily been configured to accept a standalone .aspx page where you could maybe place your secondary grid.
// This plain object is used by the call to colorbox(), please
// refer to colorbox documentation for details.
var colorboxDataExpertCV = {
height: "85%",
width: 900,
opacity: .30,
fixed: true,
iframe: true,
returnFocus: false,
href: ''
}
// ========================================================
// In the Template above, the onclick code:
// onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>'
//
// Renders to:
// onclick="ViewPDF(12345)"
//
// PdfHandlerExpertsCV.ashx is an GenericHandler that retrieves
// the CV from our database and writes the byte array to the
// colorbox iframe as an "application/pdf" content type which
// triggers native browser pdf management either by internal
// viewer or installed PDF plugin
// ========================================================
function ViewPDF( p ) {
if ( event.stopPropagation )
event.stopPropagation();
else
event.cancelBubble = true;
if ( p && p > 0 ) {
colorboxDataExpertCV.href = "/PdfHandlerExpertsCV.ashx?cvid=" + p;
$.colorbox( colorboxDataExpertCV );
}
return false;
}
Addendum
Let me make it more clear, I need to bind the data in 2nd Gridview and
display this Gridview2 in Jquery dialog .This data will be binded and
displayed in dialog from on the click event of linkbutton inside
Gridview1
As I said above, you cannot bind a GridView (server side event) and then popup a jquery ui dialog (client side event) without introducing much more complexity. You have to make sure all the data you need for the popup is available by the time you're ready to hit the button that opens the dialog.
The simplest way to accomplish this is to embed GridView2 within GridView1 and take care of the binding all at once. It's not pretty or efficient and, depending on the number of items shown in each, can slow down the page. But if you have only a few lines for each it should be acceptable.
Embed GridView2 and DataSource2 in the <ItemTemplate> of a <TemplateField> of GridView1.
Bind GridView2 in the RowDataBound event of Gridview1 using an appropriate row field or datakey field from GridView1 and then calling GridView2.DataBind().
Add a element to the same TemplateField
Refer to the jquery dialog modal form example which shows how to trigger a dialog from a button click. In your case substitute the second GridView for the Form in the example.
IMPORTANT be mindful that gridview row item id's get "mangled" so you should not use id's in the jquery calls but use jquery selectors that are based on element name plus class markers, ie: $("button.marker") for a button defined like this: <button class="marker">.
Addendum: 2015-Jun-24
CSS (<head> tag)
<link rel="stylesheet" type="text/css" href="css/smoothness/jquery-ui.css" />
<script type="text/javascript" src="Scripts/jquery-2.1.4.min.js"> </script>
<script type="text/javascript" src="Scripts/jquery-ui-1.11.4.min.js"> </script>
<style>
.btn_styling {
text-align: center;
width: 32px;
margin: 2px;
cursor: pointer;
border: 1px solid gray;
border-radius: 3px;
/* add a background image to the div
to make the div look like a button */
/* background-image: url('...') */
}
.ui-dialog-titlebar-close {
display: none;
}
</style>
HTML (.aspx)
<form id="form1" runat="server">
<div style="width: 400px;">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="user_id"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="user_name" HeaderText="User Name" SortExpression="user_name" />
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
<div id="divButton" runat="server" class="btn_styling dialog-marker" title="This could also have been a <button> element or maybe an <img> element...anything really">X</div>
<div style="display: none;">
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" />
<asp:BoundField DataField="add_edit_date" HeaderText="Date Added" SortExpression="add_edit_date" DataFormatString='{0:dd-MMMM, yyyy}'/>
<asp:BoundField DataField="add_edit_by" HeaderText="Added By" SortExpression="add_edit_by" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT email, add_edit_date, add_edit_by FROM tbl_users WHERE (user_id = #user_id)">
<SelectParameters>
<asp:Parameter Name="user_id" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BorderColor="Blue" BorderStyle="Solid" BorderWidth="1px" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT top 10 user_id, user_name from tbl_users">
</asp:SqlDataSource>
</div>
<div id="dialogContainer">
</div>
</form>
Code Behind (VB):
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim gv2 As GridView = DirectCast(e.Row.FindControl("GridView2"), GridView)
Dim sds As SqlDataSource = DirectCast(e.Row.FindControl("SqlDataSource2"), SqlDataSource)
sds.SelectParameters("user_id").DefaultValue = GridView1.DataKeys(e.Row.RowIndex).Value
gv2.DataBind()
End If
End Sub
jQuery to implement Dialog:
<script type="text/javascript">
var dialogOptions = {
autoOpen: false,
appendTo: "#dialogContainer",
modal: true,
height: "auto",
width: "auto",
title: "Dialog Title",
closeOnEscape: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
}
};
$( function() {
$( ".dialog-marker" ).on( "click", function() {
var d = $( this ).next( "div" ).first().dialog( dialogOptions );
d.dialog( "open" );
} );
} );
</script>
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.
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
});
1) If i click the view button from the grid, it has to display jquery dialog for that particular LID, but it is not working.(In the dialog, it has to show only REMARKS1 column text)
2) I have included the linkbutton(Cancel/Edit) through c# code to edit the particular row.
How can i use jquery dialog for edit/Cancel.
I have pasted my aspx webpage and C# code.It would be great if you can change this code, otherwise please provide new code.
Please find the attached image, it will show you grid and dialog box.
aspx page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="jquery/themes/dark-hive/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="jquery/jquery-1.9.0.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.core.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.widget.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.mouse.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.draggable.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.position.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.button.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.dialog.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.effect.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.effect-slide.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.effect-explode.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.effect-fade.js" type="text/javascript"></script>
<link href="jquery/themes/demos.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#example1").dialog({
modal: true,
autoOpen: false,
show: {
effect: "slide",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$('#btuser').click(function (event) {
event.preventDefault();
$('#example1').dialog('open');
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 500px;">
<asp:GridView ID="grdDisplay" runat="server" AutoGenerateColumns="False" CellPadding="1"
CellSpacing="1" Height="0px" GridLines="None" CssClass="myGrid" PagerStyle-CssClass="pager"
AlternatingRowStyle-CssClass="alt" Width="1024px" RowStyle-CssClass="RowStyle"
Font-Bold="False" Font-Names="Segoe UI" Font-Size="13px" OnRowDataBound="grdDisplay_RowDataBound">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:BoundField HeaderText="LID" DataField="l_ID" ItemStyle-Width="45px" />
<asp:BoundField HeaderText="S_Date" DataField="s_date" DataFormatString="{0:dd-MM-yyyy}" ItemStyle-Width="60px" />
<asp:BoundField HeaderText="E_Date" DataField="e_date" DataFormatString="{0:dd-MM-yyyy}" ItemStyle-Width="60px" />
<asp:BoundField HeaderText="Div" DataField="Div_type" />
<asp:TemplateField HeaderText="Remarks1" ItemStyle-Width="125px" ItemStyle-Height="25px">
<ItemTemplate>
<asp:TextBox runat="server" ID="lblreason" Text='<%# Bind("Remarks1") %>' Height="20" Width="90" ReadOnly="true" CssClass="cmdtextbox">
</asp:TextBox>
<div style="margin-top: 0px; float: right;">
<asp:Button runat="server" Width="25" Height="25" ID="btuser" CssClass="btreason" text="View" />
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Remarks2" DataField="Remarks2" ItemStyle-Width="62px" />
</asp:TemplateField>
<asp:BoundField HeaderText="Remarks3" DataField="Remarks3" ItemStyle-Width="60px" />
</Columns>
<PagerStyle CssClass="pager"></PagerStyle>
<RowStyle CssClass="RowStyle" />
</asp:GridView>
</div>
</form>
</body>
</html>
C# code*
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtmydata = new DataTable();
if (!Page.IsPostBack)
{
dtmydata = Dtthandler.GetEmData(HttpContext.Current.Session["TatID"].ToString());
//Add new column
dtmydata.Columns.Add(new DataColumn("User Action", Type.GetType("System.String")));
foreach (DataRow row in dtmydata.Rows)
{
currentdate = DateTime.Now;
Edate = Convert.ToDateTime(row[2].ToString());
strtmpCdate = currentdate.ToShortDateString();
strtmpEdate = Edate.ToShortDateString();
if (Convert.ToDateTime(strtmpCdate) <= Convert.ToDateTime(strtmpEdate))
{
row[7] = "Yes";
}
else
{
row[7] = "No";
}
//Bind data to grid
grdDisplay.DataSource = dtmydata;
grdDisplay.DataBind();
}
}
}
protected void grdDisplay_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lnkbtnCancel = new LinkButton();
LinkButton lnkbtnModify = new LinkButton();
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[7].Text == "Yes")
{
lnkbtnCancel.Text = "Cancel";
lnkbtnModify.Text = "Modify";
e.Row.Cells[7].Controls.Add(lnkbtnCancel);
e.Row.Cells[7].Controls.Add(lnkbtnModify);
//How to populate jquery dialog using this linkbutton?
}
else
{
e.Row.Cells[7].Text = string.Empty;
}
}
}
catch (Exception ex)
{
}
}
this is an example from my code - please adjust to your use:
have dialog declared like so:
<div id="dialog-form">
... // all of the elements you need in the dialog
</div>
and then in the javascript section:
$("#dialog-form").dialog({
autoOpen: false,
height: 580,
width: 800,
modal: true,
buttons: {
"Do Something": function () {
},
Cancel: function () {
$(this).dialog("close");
}
}
});
finally - on the button or element used to fire up your dialog:
onclick='$( "#dialog-form" ).dialog( "open" );'
I hope this helps.