Search This Blog

Monday, January 31, 2011

How to open popup windows in IE/Firefox and return values using ASP.NET and Javascript


In this article, we will see how to take a simple approach and create a popup window using both IE and Firefox. In the first part, we will pass in the first name from the parent page to the popup window. In the second part, the popup window will reverse the name and return the reversed string to the parent window. All set!! Let us get started.
Part 1 - Passing value to Popup window
Step 1: Open Visual Studio. Create a new website (File > New > Website). Set the location, filename and language of the project.
Step 2: In your Default.aspx, add a label (lblFName), textbox (txtFName) and a button (btnPopup). Set the ‘Text’ property of the label to ‘FirstName’. Similarly set the ‘Text’ property of the button control to ‘Show Popup’.
Step 3: Now add the popup form. Right click your project > Add New Item > Web Form > Rename form as ‘PopupWin.aspx’ and click on Add.
Step 4: In the PopupWin.aspx, add a textbox (txtReverse) and a button (btnReverse).
Well now we have two pages, Default.aspx which is the parent page and PopupWin.aspx which will be the popup page. Let us now pass a value from Default.aspx to the popup window.
Step 5: We will invoke the popup window on the button (btnPopup) click of Default.aspx. To do so, we will use Button.Attribute.Add and call a javascript function that will open the popup window. The javascript function will be contained in a seperate pop.js file which we will create shortly. Add this code in the code behind file of your Default.aspx.
protected void Page_Load(object sender, EventArgs e)
    {
        btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" + txtFName.ClientID + "');");
    } 
Over here we are passing the ClientID of the textbox. ClientID is the identifier of the server control, generated by ASP.NET. You must be wondering why I am not passing the value of the textbox directly. Well passing the control has an advantage where there is more than one control that is passed to the popup page. While returning back the values from the popup to the parent page; it helps you to decide and determine which control receives which value. Even though we will be using only one textbox for simplicity, I thought of creating a sample which can be extended later by you to suit your needs. If the use of ClientID is not clear to you, wait till we get to part 2 of this article, and I will again touch upon the subject.
Step 6: Let us now create the javascript functionality which will open the Popup. Right click your project > Add New Item > Jscript file > Rename the file to pop.js. Add the following function to the pop.js file
function InvokePop(fname)
{
        val = document.getElementById(fname).value;
        // to handle in IE 7.0          
        if (window.showModalDialog)
        {      
            retVal = window.showModalDialog("PopupWin.aspx?Control1=" + fname + "&ControlVal=" + val ,'Show Popup Window',"dialogHeight:90px,dialogWidth:250px,resizable:
yes,center:yes,");
            document.getElementById(fname).value = retVal;
        }
        // to handle in Firefox
        else
        {     
            retVal = window.open("PopupWin.aspx?Control1="+fname + "&ControlVal=" + val,'Show Popup Window','height=90,width=250,resizable=yes,modal=yes');
            retVal.focus();           
        }         
}
This function accepts the textbox control, retrieve’s the value of the textbox that needs to be reversed and passes the textbox control and its value to PopupWin.aspx through query string. This is the function which will be called on the btnPopup click.
Step 7: To wire up the .js with your asp.net pages, add a link to the javascript file in both the pages as shown below:
Default.aspx
<head runat="server">
    <title>Parent Page</title>
    <script type="text/javascript" src="pop.js"></script>
</head>
PopupWin.aspx
<head runat="server">
    <title>Popup Page</title>
    <script type="text/javascript" src="pop.js"></script>
</head>
Step 8: In the code behind file of PopupWin.aspx, add the following code at the Page_Load() to retrieve the value from the querystring and display the value in the TextBox ‘txtReverse’, placed in the popup window.
protected void Page_Load(object sender, EventArgs e)
    {
        txtReverse.Text = Request.QueryString["ControlVal"].ToString();
    }

If you are eager to test the value going from Parent page to the popup window, you can do so now. Make Default.aspx as ‘Set as Start page’ and run the sample. Enter your name in txtFName TextBox and click on Show Popup button. A popup window opens with the value entered in the Parent page.
Part 2 - Passing value from Popup window to the Parent page
In this second part, we will reverse the string and pass the reversed string back to the parent page. To do so, follow these steps:
Step 1: Add additional functions to the pop.js file which will reverse the string and return the string back to the parent page.
// pop.js
function ReverseString()
{
         var originalString = document.getElementById('txtReverse').value;
         var reversedString = Reverse(originalString);
         RetrieveControl();
         // to handle in IE 7.0
         if (window.showModalDialog)
         {             
              window.returnValue = reversedString;
              window.close();
         }
         // to handle in Firefox
         else
         {
              if ((window.opener != null) && (!window.opener.closed))
              {              
                // Access the control.       
                window.opener.document.getElementById(ctr[1]).value = reversedString;
              }
              window.close();
         }
}
function Reverse(str)
{
   var revStr = "";
   for (i=str.length - 1 ; i > - 1 ; i--)
   {
      revStr += str.substr(i,1);
   }
   return revStr;
}
function RetrieveControl()
{
        //Retrieve the query string
        queryStr = window.location.search.substring(1);
        // Seperate the control and its value
        ctrlArray = queryStr.split("&");
        ctrl1 = ctrlArray[0];
        //Retrieve the control passed via querystring
        ctr = ctrl1.split("=");
}
As you saw in part 1, the value was passed from the parent window to the popup window and was kept in the txtReverse TextBox. The function ReverseString() retrieves the value from this textbox and passes the string to the Reverse() function which reverses the string. The reversed string is then kept in the ‘reversedString’ variable. The ‘RetrieveControl’ splits the query string and identifies the control in the parent page to which the reversed string value is to be sent.
Note: If you observe, in the IE implementation, I am not really making use of the RetrieveControl(), however in Firefox I am. If you remember, in the beginning of part1 , I had mentioned the use of ClientID, using which both controls and their values can be passed to determine which control recieves which value. This is especially needed when there are multiple controls. Well the RetrieveControl seperates the different controls and you can use the variables in this method to return values to the respective contro.l
The value is then returned to the parent window and the popup window is closed.
Step 2: Now in order to use these newly added javacript functions, just call the ReverseString() function on the btnReverse click. To do so, add the onclick attribute to the btnReverse.
<input class="button" type="button" id="btnReverse" value="Reverse value back" onclick="ReverseString();"/>
That’s it. Now test the code. Pass your name from the Parent window to the Popup window and then reverse the string and pass it back to the Parent window.

Deleting Multiple Rows in a GridView


 A gridview allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with gridview.
The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose ‘Relationships’. Select all the relationships like FK_Orders_Employees,  FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we will get a constraint violation exception if we do not do so.
Once we are through with the task of removing the relationships in the Employee table, let us explore the steps to create a gridview with functionality to delete multiple rows at a time
Configure the connection of SqlDataSource to point to the Northwind database.  Create queries for the Select and Delete commands. The resultant code will look similar as given below

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
    SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
    DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
       <DeleteParameters>
           <asp:Parameter Name="EmployeeID" />
       </DeleteParameters>
</asp:SqlDataSource>
Once the SqlDataSource has been configured, bind the gridview with this data source.

To create a checkbox in each row, follow these steps:
1.    Create a TemplateField inside the <Columns> to add custom content to each column.
2.    Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.
<asp:TemplateField>
       <ItemTemplate>
             <asp:CheckBox ID="chkRows" runat="server"/>
      </ItemTemplate>
 </asp:TemplateField>
This will add a checkbox to each row in the grid.

Add a button control, and rename it to btnMultipleRowDelete.
The resultant markup in the design view will look similar to the code below :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
  
   <Columns>
      <asp:TemplateField>
          <ItemTemplate>
            <asp:CheckBox ID="cbRows" runat="server"/>
          </ItemTemplate>
       </asp:TemplateField>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
   </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
   <DeleteParameters>
       <asp:Parameter Name="EmployeeID" />
   </DeleteParameters>
</asp:SqlDataSource>
<asp:Button
   ID="btnMultipleRowDelete"
   OnClick="btnMultipleRowDelete_Click"
   runat="server"
   Text="Delete Rows" />
In Code behind file (.cs) for C# and (.vb) for VB.NET, code the button click event. Our code will first loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command.
protected void btnMultipleRowDelete_Click(object sender, EventArgs e)
{
        // Looping through all the rows in the GridView
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox checkbox = (CheckBox)row.FindControl("cbRows");
            //Check if the checkbox is checked.
//value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
            if (checkbox.Checked)
            {
                // Retreive the Employee ID
int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
// Pass the value of the selected Employye ID to the Delete //command.
SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString();
                SqlDataSource1.Delete();
            }
        }
 }
Run the code, and select a few rows in the grid. ‘Delete Rows’ button, the selected rows get deleted. Rather than deleting rows one at a time, deleting them in a batch is a good practice.

Tuesday, January 25, 2011

How to restrict size of file upload in asp.net


I have one page that contains one file upload control to accept files from user and saving it in one folder. I have written code to upload file and saving it to folder it’s working fine after completion of my application my friend has tested my application like he uploaded large size file nearly 10 MB file at that time it’s shown the error page like “the page cannot displayed”. 

Again I have search in net I found that file upload control allows maximum file size is 4MB for that reason if we upload file size larger than 4MB we will get error page like “the page cannot displayed” or “Maximum request length exceeded”.

After that I tried to increase the size of uploaded file by setting some properties in web.config 
file like this 


<system.web>
<httpRuntime executionTimeout="9999" maxRequestLength="2097151"/>
</system.web>


Here httpRuntime means

Configures ASP.NET HTTP runtime settings. This section can be declared at the machine, site, application, and subdirectory levels.

executionTimeout means

Indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.

maxRequestLength means

Indicates the maximum file upload size supported by ASP.NET. This limit can be used to prevent denial of service attacks caused by users posting large files to the server. The size specified is in kilobytes. The default is 4096 KB (4 MB).

After that write the following code in aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>

After that write the following code in code behind


protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentLength < 20728650)
{
try
{
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "File size exceeds maximum limit 20 MB.";
}
}
}


After that write the following code in web.config

<system.web>
<httpRuntime executionTimeout="9999" maxRequestLength="2097151"/>
</system.web>