AspdotnetCodes.com
ASP.NET 3.5 Web Hosting – Click Here
 
Articles Subscribe for our Articles Updates
Books
Resources
Downloads
Free Tech Magazines
Archives
Softwares
Newsletter
Suggest Us
Link to Us
 Ajax ModalPopup Extender in Asp.Net GridView Control
Posted by Moderator1 on 7/18/2007 5:16:14 PM Category: AJAX
Total Views : 59556
Add to my favorites
Email to friend
  
Introduction
This article helps you more to explore the ModalPopup Extender integrated with Asp.Net GridView control. By reading this article, you will understand the way to show dynamic data in the ModalPopup, edit the data in the ModalPopup extender and save it into database by making a postback.
What we are going to do?

The basic idea of this article is to fetch data from the database, bind it with Asp.Net GridView control, and then we are going to show the values in the server controls placed in the ModalPopup extender and perform an edit/update function from the ModalPopup extender itself. To achieve this, we are going to use WebService which will return the required data as XML, this XML data is captured in the client-side by JavaScript’s XMLDOM object, then we are going to process the XML to fill the controls in the ModalPopup extender. These data can be changed and on postback, these data will be saved in the database. You can place any server controls in the ModalPopup extender.
  Sample Scenario

For demonstration, we are going to use customer information from a table called Customers. The primary key column is customer code and its field name is ‘Cus_Code’. The other columns in the customer table is customer name [Cus_Name], Gender [Cus_Gender], City[Cus_City], State [Cus_State] and Customer Type [Cus_Type]. We are going to use TextBox, DropDownList and HiddenField controls in the ModalPopup extender to manipulate these data.

Make GridView control

In your Ajax enabled website’s aspx page, add a GridView control in it and set the DataKeyNames to your primary key (in this case it is Cus_Code), and bind it with your Data source control. Or if you want to bind the GridView control from code-behind, create a private method to fetch data from the database and bind it as follows
private void FillGridViewWithCustomerInfo()
{
    string sql = "Select * from customers"; 
    SqlDataAdapter da = new SqlDataAdapter(sql, “Your connection string”); 
      DataTable dt = new DataTable(); 
      da.Fill(dt); 
    GridView1.DataSource = dt; 
    GridView1.DataBind();
}
In the Page Load event, call this method to bind the GridView control with the data from the database. Then add a TemplateField column to the GridView. In the ItemTemplate section of this column, drag and drop a HyperLink control, specify the Text property as ‘Edit’. We have to add an client-side onclick event to this hyperlink to show the ModalPopup extender. In the GridView control’s RowDataBound event, add the following code.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
        HyperLink HyperLink1 = (HyperLink)e.Row.FindControl("HyperLink1"); 
        HyperLink1.Attributes.Add("onclick", "ShowMyModalPopup('" + GridView1.DataKeys[e.Row.RowIndex].Value + "')"); 
    }
}
The second line of the above code, adds the onclick attributes to the HyperLink1, with ShowMyModalPopup as a JavaScript function which takes the value from the DataKeyNames of the GridView control. A DataKeyNames property is an array that contains the names of the primary key fields for the items displayed in a GridView control.

So far, we made all the basic things ready for the GridView control to display data. Now you run the application, the GridView control will be populated with data from the customer table. When the hyperlink is clicked, the ModalPopup extender should come to action with the corresponding data from the selected row. We are going to do this with the help of Webservice method, which will return specific row data in an XML format. This webservice method will be called by the JavaScript method ShowMyModalPopup, and then we will process the XML and extract the data to display in the controls of the ModalPopup extender.
 
Make the WebService.asmx

In your application, add a new WebService file and write a method to fetch single row from the customer table and return it in XML format. The webmethod will be as follows
[WebMethod]
public string FetchOneCustomer(string customerid)
{
  string sql = "select * from Customers where cus_code=" + customerid;
  SqlDataAdapter da = new SqlDataAdapter(sql, “Your connection string”);
  DataSet ds = new DataSet();
  da.Fill(ds);
  return ds.GetXml();
}
The above method will take customer code as argument and fetch the row and it will return the row as XML. So far GridView contol and WebService is ready. Now we can start to work on the ModalPopup extender to display the data for the corresponding selected row from the GridView control.

Design ModalPopup Extender

Drag and drop a ScriptManager, a ModalPopup Extender and a Panel control. Set the PopupControlID and TargetControlID of the ModalPopup Extender as ‘Panel1’. In the Panel control, you put 3 Textboxes to display Customer name, City and State and 2 DropDownList controls to take Gender and Customer Type. Also add a Hidden field to store Customer Code, and 2 Buttons to perform Update and Cancel action. Add a ServiceReference to the ScriptManager and point it to the WebService.asmx. Below we provide the sample code for ScriptManager, ModalPopup Extender and the Panel control

Click here to view Source Code HyperLink
 
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ScriptManager>

<asp:Panel ID="Panel1" runat="server" BackColor="LightGray" Height="269px" Width="428px" style="display:none">
Customer # : <asp:Label ID="lblCode" runat="server" Text="Label"></asp:Label> <asp:HiddenField ID="hidCusCode" runat="server" /> <br/>
Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/>
Gender: <asp:DropDownList ID="cmbSex" runat="server"> <asp:ListItem Value="M">Male</asp:ListItem> <asp:ListItem Value="F">Female</asp:ListItem> </asp:DropDownList><br/>
City:<asp:TextBox ID="txtCity" runat="server"></asp:TextBox><br/>
State:<asp:TextBox ID="txtState" runat="server"></asp:TextBox><br/>
Type:<asp:DropDownList ID="cmbType" runat="server" > <asp:ListItem Value="Retailer">Retailer</asp:ListItem> <asp:ListItem Value="Wholesale">Wholesale</asp:ListItem> </asp:DropDownList><br/>
<asp:Button ID="Button1" runat="server" Text="Update" OnClick=" Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Cancel" />
</asp:Panel>

<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" PopupControlID="Panel1" TargetControlID="Panel1" BackgroundCssClass="modalBackground" CancelControlID="Button2" OnCancelScript="HideModalPopup()"> </cc1:ModalPopupExtender>  
So the ModalPopup extender has to appear on the screen along with the data of the corresponding row whenever the user clicks the HyperLink in the GridView control. For this we have write two JavaScript functions, one to show the ModalPopup window with the data and another function to display the data in the control of the ModalPopup extender.

The first JavaScript function is ShowMyModalPopup, which we already set in the HyperLink’s client-side onclick in the GridView’s RowDataBound event. This JavaScript function will be as follows

 
function ShowMyModalPopup(customerid)

 var modal = $find('ModalPopupExtender1'); 
 modal.show(); 
 WebService.FetchOneCustomer(customerid,DisplayResult);
}

In the above function, we find the ModalPopup Extender in the web page and show it. The next line of code is calling the webservice method from the JavaScript by passing the customer code and a JavaScript function name to process the result returned by the webmethod. This is the concept of consuming webservice with Asp.Net Ajax. The DisplayResult function takes an argument which is the resultant XML data come from the webservice method, process it with all browser compatibility issues, remove whitespaces in the XML data and set the values to the corresponding server controls in the ModalPopup Extender’s Panel control. Look carefully at the code below to set the values from XML data to Asp.Net server controls in the ModalPopup window.
function DisplayResult(result)
{
  var doc; 
  if (window.ActiveXObject) 
  { 
    doc=new ActiveXObject("Microsoft.XMLDOM"); 
    doc.async="false"; 
    doc.loadXML(result); 
  } 
  else 
  { 
    var parser=new DOMParser(); 
    var doc=parser.parseFromString(result,"text/xml"); 
  } 

  var root=doc.documentElement.childNodes; 
  var tags; 

  for(var i=0;i<root.length;i++) 
  { 
    if (root[i].nodeType==1) 
    { 
        tags=root[i].childNodes; 
    } 
  } 

  for(var i=0;i<tags.length;i++) 
  { 
    if (tags[i].nodeType==1) 
    { 
      var xmlvalue=tags[i].childNodes[0].nodeValue; 

      switch (tags[i].nodeName) 
      { 
        case "Cus_Code": 
        var label=document.getElementById('lblCode'); 
        label.innerHTML=xmlvalue; 
        document.getElementById('hidCusCode').value=xmlvalue; 
        break; 
        case "Cus_Name": 
        document.getElementById('txtName').value=xmlvalue; 
        break; 
        case "Cus_City": 
        document.getElementById('txtCity').value=xmlvalue; 
        break; 
        case "Cus_State": 
        document.getElementById('txtState').value=xmlvalue; 
        break; 
        case "Cus_Type": 
        document.getElementById('cmbType').value=xmlvalue; 
        break; 
        case "Cus_Sex": 
        document.getElementById('cmbSex').value=xmlvalue; 
        break; 
      } 
    }
  }
}
Close ModalPopup Extender from JavaScript

To close the ModalPopup Extender, specify the CancelControlID to the Cancel Button and specify the OnCancelScript values as HideModalPopup(). The JavaScript code for HideModalPopup function is

 function HideModalPopup()
{
  var modal = $find('ModalPopupExtender1');
  modal.hide();
}

Save everything, run the application. You can see the GridView control with customer data, when you click on the HyperLink, ModalPopup Extender will appear and the controls will be filled the the data from the selected row. If you click on the cancel button, the ModalPopup will get closed.

Edit Data From ModalPopup Extender

To edit data in the ModalPopup Extender and to save it in the database, we need to perform PostBack from a ModalPopup Extender. Follow the steps to make postback from ModalPopup Extender,

Step 1: Add the below code in Page load event

Button1.OnClientClick=String.Format("fnClickUpdate('{0}','{1}')", Button1.UniqueID, "");

Step 2: Add the below JavaScript function in the <script> section.

function fnClickUpdate(sender, e)
{
  __doPostBack(sender,e);
}
These two steps will help the ModalPopup Extender to perform Postback actions, and the Button1’s server side click event will get fired, which in turn takes the data from the ModalPopup controls and save it into the database.

To implement this we need to put a Hidden field inside the Panel control and specify its ID as hidCusCode. This Hidden field will hold the primary key, that is the unique customer code, which we are going to use to update the records in the database. The value for this hidden field will be set in the DisplayResult JavaScript function.

Double click on the Update Button, it will create an Button1_Click event in your code-behind file. Write the code here to update the database record with the modified data and call FillGridViewWithCustomerInfo method to bind the GridView control with the updated data as follows
 
protected void Button1_Click(object sender, EventArgs e)
{
  string sql = "Update Customers Set Cus_Name=’”+txtName.Text+”’, others_fields=other_controls.Text Where Cus_Code="+hidCusCode.Value; 
  SqlConnection conn = new SqlConnection(“Your Connection String”); 
  conn.Open(); 
  SqlCommand cmd = new SqlCommand(sql, conn); 
  cmd.ExecuteNonQuery(); 
  conn.Close(); 

  FillGridViewWithCustomerInfo();
}
Save your application, view it in your browser. You can view GridView Control with customer data, click on the 'Edit' link, ModalPopup Extender will appear with data from the selected row, change something and click on the Update Button. Page will get postback and data will be updated in the database and showed in the GridView control.
Click here to view our Sample ModalPopup with GridView control
 
 
Viewer's Comments
Posted by Jakal on 7/27/2007 11:16:00 AM
Thanks for the article. Found it very useful in implementing modal popop dynamically.
 
Posted by shrouk on 7/30/2007 11:47:39 PM
hi, your sample code for ScriptManager, ModalPopup Extender and the Panel control does not show! is that an collapsible panel, becuase it is not working, neither the link beside it (the one that says: Click here to view Source Code HyperLink) please check! your code has been most helpful for me so far. But i can not do anything without that part Thnx in advance shrouk
 
Posted by Mia on 8/3/2007 9:42:57 AM
Hi shrouk, the sample code doesn't show if you link through 123asp, but it shows in http://www.aspdotnetcodes.com/Ajax_ModalPopup_PostBack_GridView.aspx
 
Posted by kevin on 8/14/2007 2:54:26 PM
Great article, I'm trying to implement this in a site that I'm building. I'm using the Clubsite starter kit, and am working in VB, so obviously these steps need to be tweaked a bit. Is there an guide on how to implement this in VB? I think I've got the WebService created in VB, but nothing else. Thanks! Kevin
 
Posted by Angela on 8/14/2007 9:28:11 PM
I am so grateful for people who give examples on the web. I am working with creating my own simple page that allows someone to enter categories...However, the hyperlink is not working...I am extremly new to 2.0 and am an old web developer is classic asp who has worked with the messy side for DOM and AJAX programming client side. I am finding it fustrating trying to go through another layer to get what I want done (which I could simply write).. Feel like I am an old Assembly coder...trying to l
 
Posted by Angela on 8/14/2007 9:30:29 PM
okay previwous comment got truncated would have been nice to know upfront instead of a light greay back ground saying 500 letters in a place my eye would not follow to when filling out this form. Anyway, is there any chance you could give a full example including the .cs and the aspx code? It would help me out greatly....
 
Posted by Odiaz on 8/29/2007 3:31:55 PM
Greate Article. I am getting an error when the modal screen popsup. WebService is undefined. When I invoke the webservice outside of this app i see the dataset comming back the way its supposed to. Anyone else have this challenge? thanks
 
Posted by Ratnakar Garikipati on 10/8/2007 6:29:40 PM
nice post but would have been even better if you could show the changed values in the grid without refreshing the page.
 
Posted by raghav on 10/9/2007 11:16:57 AM
hello... can u send me ur "Grid view, modal popup " solution in asp.net "vb" language. I hv tried so many days but I m unable update contains in "modal popup". Plz help me...... waiting for ur help.
 
Posted by Stéphane on 10/19/2007 9:29:35 PM
Really, really great article. It's just what I was looking for (for a few days...). I found a lot of examples with an update panel to hide the postback to the server but your example fit the bill perfectly. Thanks a lot
 
Posted by Kalpen on 10/30/2007 1:06:04 PM
Thank you very much for this article. I have used this one and customised it to fit my need but I am running into couple of problems. 1) When I click on a grid item, unlike your sample application, my page does complete post back, loads all the data on the page and then it displays ModalPopup panel. It would be great if simply displays the panel without reloading the entire page. 2) Also, I have a dropdown and a checkbox on that panel. I can operate dropdown and change selection to whatever
 
Posted by sfbfsdh on 11/12/2007 2:40:27 AM
sdfsdf
 
Posted by Hannah on 11/13/2007 11:11:46 AM
For some reason, I can't get the modal to popup! Can anyone give me a hand? Please... Thx.
 
Posted by Ambuj on 11/16/2007 5:13:25 AM
Excellent article, solved my problem!
 
Posted by Ben on 11/26/2007 5:54:54 AM
Fantastic Article! Thank you so much for doing this! As a helper to anyone else out there who can't invoke the WebService through javascript lamke sure that you have _ defined just before the Class definiyion. _ _ Public Class WebService This allows javascript to see the WebService class for calling.
 
Posted by Ben on 11/26/2007 5:56:53 AM
Sorry my post got rendered as html. make sure that ScriptService() is defined just before the class definition in your WebService.asmx < ScriptService() >_
 
Posted by Ajax on 12/14/2007 7:31:07 AM
werrrrrrrrrrrrrrrrrrrr
 
Posted by subramanyam on 12/15/2007 8:41:36 AM
good article! very use full thanku very much
 
Posted by Mark on 12/19/2007 10:55:25 AM
Great one. Wish this was in VB.Net
 
Posted by nmnm on 12/31/2007 4:47:45 AM
bnmmmmmmmmmmmmmmmmmmm