ModalPopupExtender Example for Editing Rows in a GridView (Master/Detail Scenario)
The web application I am currently working on is a data-centric, internal facing application targeted at the knowledge workers within our enterprise. A majority of the pages are our core 'search' pages that contain a GridView and a number of input elements for entering search criteria. Each row in our GridViews contain a hyperlink to a supporting 'details' page that has additional information for the selected row - usually contained in a DetailsView. Our standard for implementing this has been to render the values for the GridViews primary key column as a hyperlink that takes the user to the details page passing the PK through the query string. This all works fine and our users seem to be OK with this type of naviagation. But when I was recently doing some work with the ModalPopupExtender, I was curious if we could improve this flow by keeping the user on the main search page by moving the DetailsView to the ModalPopupExtender. See the screen shot below or the live demo for an example.
I did a few google searches, and sure enough there were some people doing this (here and here). I took a similiar approach to the second article, but with a few minor tweaks. I uploaded a live demo of these pages so you can check out the behavior (I kept the styling to a minimum as usual). The code for this example is straight-forward except for the following 3 items:
1. The ModalPopupExtender requires the TargetControlID property to be set. Because of this I created a hidden button so this error doesn't occur. For this example, we don't need to set a control to trigger the popup because we are always explicitly calling Show() on the popup when the Details button is clicked).
2. The DetailsView for the selected row is contained in an updatepanel with the UpdateMode set to Conditional. This is done because we want to make sure that the control is only updated from the Details button click handler and not when the Customers GridView is sorted or paged through
3. We are explicitly calling Show on the ModalPopup to display the DetailsView from the 'Details' button click event. This is the only action that triggers the ModalPopup from being made visible
Also, I didn't actually implement an update because I don'y want my northwind database getting messed up. Hopefully this will get you enough of a start that implementing the update will not be a huge problem.
Here is the markup for the page, Enjoy!
<%@ Page Language="C#" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %> <!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 id="head" runat="server"> <title>Master Details Example</title> <script runat="server"> /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void BtnViewDetails_Click(object sender, EventArgs e) { // get the gridviewrow from the sender so we can get the datakey we need Button btnDetails = sender as Button; GridViewRow row = (GridViewRow)btnDetails.NamingContainer; // extract the customerid from the row whose details button originated the postback. // grab the customerid and feed it to the customer details datasource // finally, rebind the detailview this.sqldsCustomerDetails.SelectParameters.Clear(); this.sqldsCustomerDetails.SelectParameters.Add("customerid", Convert.ToString(this.gvCustomers.DataKeys[row.RowIndex].Value)); this.dvCustomerDetail.DataSource = this.sqldsCustomerDetails; this.dvCustomerDetail.DataBind(); // update the contents in the detail panel this.updPnlCustomerDetail.Update(); // show the modal popup this.mdlPopup.Show(); } </script> <style> .modalBackground { background-color:Gray; filter:alpha(opacity=70); opacity:0.7; } </style> </head> <body> <form id="form" runat="server"> <asp:ScriptManager ID="scriptManager" runat="server" /> <div> <asp:SqlDataSource ID="sqldsCustomers" runat="server" SelectCommand="select customerid, companyname, contactname, contacttitle from dbo.customers" SelectCommandType="Text" ConnectionString="todo" /> <asp:SqlDataSource ID="sqldsCustomerDetails" runat="server" SelectCommand="select * from dbo.customers where customerid=@customerid" SelectCommandType="Text" CancelSelectOnNullParameter="true" ConnectionString="todo"/> <p style="background-color:AliceBlue; width:95%"> Example of using a ModalPopupExtender to edit the indivdual rows of a GridView.<br /> To test out the functionality, click the Details button of any of the rows and watch what happens.<br /> </p> <br /> <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="lblTitle" runat="server" Text="Customers" BackColor="lightblue" Width="95%" /> <asp:GridView ID="gvCustomers" runat="server" DataKeyNames="customerid" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true" PageSize="10" DataSourceID="sqldsCustomers" Width="95%"> <AlternatingRowStyle BackColor="aliceBlue" /> <HeaderStyle HorizontalAlign="Left" /> <Columns> <asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px"> <ItemTemplate> <asp:Button ID="btnViewDetails" runat="server" Text="Details" OnClick="BtnViewDetails_Click" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="customerid" HeaderText="ID" SortExpression="customerid" ReadOnly="true" /> <asp:BoundField DataField="companyname" HeaderText="Company" SortExpression="companyname" ReadOnly="true" /> <asp:BoundField DataField="contactname" HeaderText="Name" SortExpression="contactname" ReadOnly="true" /> <asp:BoundField DataField="contacttitle" HeaderText="Title" SortExpression="contacttitle" ReadOnly="true" /> </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> <asp:Button id="btnShowPopup" runat="server" style="display:none" /> <ajaxToolKit:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlPopup" CancelControlID="btnClose" BackgroundCssClass="modalBackground" /> <asp:Panel ID="pnlPopup" runat="server" Width="500px" style="display:none"> <asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="lblCustomerDetail" runat="server" Text="Customer Detail" BackColor="lightblue" Width="95%" /> <asp:DetailsView ID="dvCustomerDetail" runat="server" DefaultMode="Edit" Width="95%" BackColor="white" /> </ContentTemplate> </asp:UpdatePanel> <div align="right" style="width:95%"> <asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="alert('Sorry, but I didnt implement save because I dont want my northwind database getting messed up.'); return false;" Width="50px" /> <asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" /> </div> </asp:Panel> </div> </form> </body> </html>

Comments
It seems some of the text was cut off by the page width in your code above.
Could you kindly repost or let us donload the code? (VB and C#?)
Could you expain or provide code to show model pop up on page load insted invoking by Button Click events
hi sir,
I am student, learning asp.net,
i have a problem in updting details view.
pls, can u provide me the update part of your program sir
Matt,
Did you ever experience any issues with validators inside ModalPopup ? I have been trying to figure out why client side validation fails when using RequiredFieldValidator inside ModalPopupControl (which is displayed when editing GridView row). After clearing a field and pressing tab to proceed to next field, validator is activated. But when pressing Update-button, I can see that validator gives an error message, but at the same time ModalPopup disappears and data is processed (so that I can update an empty value to DB which is something that I don't want)
This article would have been brilliant if it had shown how to save. I can understand why there is no save in the demo, but why not in the code shown above, or the download. I have tried hard to work it out, but failed. Is there anyone who can help please. I am sure an answer would be greatly appreciated by many people.
Thanks.
Sorry Mat, but the save data portion of the demo is, like, totally not obvious.
How about an update to the download so that we are both happy. You still save your database, and your readers will be enlightened!
Thanks.
About the update, i realized the following function... please, tell me what you think about this option :
protected void SaveDetails(object sender, EventArgs e)
{
IOrderedDictionary keyList = dvCustomerDetail.DataKey.Values;
// Get the ArrayList objects that represent the key values.
ArrayList values = new ArrayList(keyList.Values);
// Get the key field and value for the current record.
String customerKey = values[0].ToString();
this.sqldsCustomerDetails.UpdateParameters.Add("customerid", customerKey );
this.sqldsCustomerDetails.UpdateParameters.Add("companyname", ((TextBox)dvCustomerDetail.Rows[0].Cells[1].Controls[0]).Text);
...
this.sqldsCustomerDetails.Update();
this.gvCustomers.DataBind();
}
Hi Sir,
I am using "Ajax Extentions" that meet some issues such as I'm using master pages with my tab control on a content page.
how to click "BtnViewDetails_Click" on first tab to display all data have customerid=@customerid on second tab!
pls, can u provide me the sample program sir!
Paul
Very nice Matt, works a charm... but... please tell me the secret... how do I stop the pop up panel "remembering" the scroll postion! I have a pop up where the content exceeds the depth sometimes. This means I scroll down to click the close button and the next time the window pops up, it scrolls to wherever I was last time!
It's driving me mad! Can anyone help put me out of my misery please? I just want it to always scroll back to the top when I open the popup!
Hi Matt,
One question, As I keep on ModalPopupExtender to make PostBack?
Thanks.
thanks for the GREAT post! Very useful...
i am chinese ,i have a problem,where are your connectionString?
Your ConnectionString is in your web.config (in the section) . Then, you select your ConnectionString in the DataSource.
Hi Matt,
With asp.net, I have yet to figure out how to best implement a really neat feature and that is the COPY option on each row on the GridView.
When the Copy is clicked on a row, it goes to the Detail View with all the fields prefilled from the row that was clicked and allow user to make any changes and INSERT a new record - the detail view being shown in INSERT Mode.
Ideally - I would like to reuse the Detail View for both UPDATE and INSERT mode where UPDATE (makes the key field readonly) while INSERT allows you to set the key or hide the key if it is a autonumber/integer assigned by database using the IDENTITY column.
Thanks
Mad
I agree with tim...The most difficult part is how to update when ok button is clicked?
Can anyone tell me how can I use update command...?
Thanks!!
I want my database get messed up!!
hi how u show the loading gif file whe i click the view details button inside the grid........
How can I add the value in a gridview column directly from the modal popup extender. I dont want to update the datasource, but want to directly show the value from modalpopup textbox to a gridview column.
Thanks.
works like a charm!
however... can't figure out what the save portion is supposed to be like. is there still no update on this?
appreciate it much! thanks!
great work, by the way.
Here is what I did for the save, although its probably not the most elegant solution...
Note: The controls below are not in the tutorial. It has been adapted to suit my needs. This goes in the click event of your save button.
Dim alertid As String = dvConfiguration.DataKey.Value.ToString
Dim description As TextBox = CType(dvConfiguration.FindControl("txtdescription"), TextBox)
Dim strSQL As String = "mm_UpdateAlert"
Dim con As New SqlConnection(AuditConnectionString)
Dim cmd As New SqlCommand(strSQL, con)
cmd.CommandType = CommandType.StoredProcedure
Dim pDescription As SqlParameter = cmd.Parameters.Add("@description", SqlDbType.VarChar)
pDescription.Value = description.Text
Dim pAlertId As SqlParameter = cmd.Parameters.Add("@alertid", SqlDbType.VarChar)
pAlertId.Value = alertid
Try
con.Open()
cmd.ExecuteNonQuery()
con.Close()
The idea is to pull the datakey of the details view for the "where" portion of the SQL clause. Then declare all the controls in your details view so you can grab their text values. From there its just a matter of inputting them into your SQL command string for the update.
Thanks Matt for writing such a great tutorial!
solved my problem.
really good article.
thank u very much.
Hello Sir,
I would like to do the same thing but with a listview instead of a gridview. Is it possible?
Also, I would like to insert data to the listview using the popout method...
Thanks,
Hi Matt,
I noticed in your live demo that there's an animation playing before the modal popup display, but I can't find any reference to that in the sample code. Can you kindly please share how you achieve that? Sorry but I'm a beginner to ajax.net. Thank you very much
Paul I'm having the same problem...
"how do I stop the pop up panel "remembering" the scroll postion!"
Matt?
Cool Article. Thanks For Excellent Tip.
Hi,
I am new with ajaxtoolkit. we are using modalpopup for project at work. Now I have to include a TabContainer within the modalpopup. When I add a textbox within the TabContainer/TabPanel, the textboxes are null. I have tried the textboxes outside the TabContainer and they are fine. I am able to render the textboxes but once I try to save and get the values from the textboxes, I received errors saying they are null.
Could anyone help please? Thanks so much!
requirePermission attribute is not declared...this type of lot of problems i m facing while run ur downloaded program
Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. (D:\Neetu\Projets Backup\webroot\web.config line 40)
this is another error...and a lot of errors....please help me
Please tell us how to update/save the record from here
I have converted the code to VB but i'm getting the following error on this line: Me.mdlPopup.Show() Error = "mdlPopup is not a member of 'Page_Name'". Any idea's?
How to Check there TextBox's date is validate when USE ModelPopulExtender
For all that wanted to know how to get it to scroll back to the top. You can do this with som script code:
Take note of the scrollTo(x,y) function. You will have to modify those arguments to scroll to a position relative to your webpage. Hope this helps.
Folks,
Has anyone tried including the cascadingdropdown control in the modalpopup panel.
I have attempted this several times but no joy. All sorts of problems on postback
In your live demo, when you enter any html code(or just even a "
eg. when you first time click "details" button, in any textbox(eg. in City texbox, enter ) and click no matter "Save" or "Close". And then click on any "details" button again, then, you will see the error.
Do you know how/why this happens?
oh. it seems I cannot enter a > in the comment too.
In your live demo, when you enter any html code(or just even a "<"), it will cause a 500 error from server.
eg. when you first time click "details" button, in any textbox(eg. in City texbox, enter "<b>") and click no matter "Save" or "Close". And then click on any "details" button again, then, you will see the error.
Do you know how/why this happens?
Pls show update/save code here..
Thanks in anvance
I have created an example that includes updating/saving the data. You can check it out here
I want to have the id of the textbox inside the DetailsView.How it can be achieved?
Validators will not work on modal popup and you will require to create item templates for it and bind them individually
Just out curiousity. I have a mainpage that calls a usercontrol that is in a modal popup. The usercontrol has a gridview and I want to implement your modal popup detail example. Is it possible to nest modal popup within another one? Is that bad design?
Saved my day! Was digging asp.net forum and found this link. Very valuable. Code is easy to understand.
Keep adding more, Matt.
Best wishes
Tom
my page is posting back while modalpopupextender is displaying...please help me
hi anybody help me out how I can do with postgressql its urgent and just tell me where should I change code or just give me code if it is possible
( I want to transfer data from parent widnow to modalpopup and then after updating in modalpopup go back to parent window with new value.
Please help me out its really very urgent
Thanks a lot in advance
Bons
hiiiiiiiii
plese provide me the save button code to update the values of details view