Infolink

 

Search This Blog

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Nov 10, 2012

Create Html Table Dynamically

The following code dynamically creates a table with five rows and four cells per
row, sets their colors and text, and shows all this on the page. The interesting detail is that no control tags are declared in the .aspx file. Instead, everything is generated programmatically.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class DynamicTable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HtmlTable table1 = new HtmlTable();

        // Set the table's formatting-related properties.
        table1.Border = 1;
        table1.CellPadding = 0;
        table1.CellSpacing = 0;
        table1.BorderColor = "red";

        // Start adding content to the table.
        HtmlTableRow row;
        HtmlTableCell cell;
        for (int i = 1; i <= 3; i++)
        {
            // Create a new row and set its background color.
            row = new HtmlTableRow();
            row.BgColor = (i % 2 == 0 ? "lightgreen" : "lightgray");
            for (int j = 1; j <= 5; j++)
            {
                // Create a cell and set its text.
                cell = new HtmlTableCell();
                cell.InnerHtml = "Row: " + i.ToString() + "<br />Cell: " + j.ToString();
                // Add the cell to the current row.
                row.Cells.Add(cell);
            }

            // Add the row to the table.
            table1.Rows.Add(row);
        }

        // Add the table to the page.
        this.Controls.Add(table1);
    }
}

Oct 27, 2012

Remote Scripting with IFRAME

Before you can exchange data between frames, you must first get access to the iframe's document object. There are 3 ways of doing this:

Three Methods

Method 1 - The iframe page can use it's own javascripts to transfer and place the data into the parent.

Method 2 - The iframe page can pass its document object as an argument to a function in the parent, thereby allowing the parent to retrieve data from the iframe.

Method 3 - Place an onload event handler in the iframe tag in the parent document (this page). This method does not work with Netscape 6.

We'll look at each of the methods below. For the sake of clarity, the iframes used in the following examples will be visible. In practice, they would be hidden using the technique discussed in the previous page.

Method 1

The parent page contains a form with a list of States. When you select a State and the results are returned in iframe name="repIframe", the iframe moves the data up to div id="results1" in this page using this script:

<script>
// - this is the script in the iframe results page
var reps = document.getElementById('state_reps').innerHTML;
parent.document.getElementById('results1').innerHTML = reps;
</script>

Method 2

Once again, we're going to use the form below to get a list of State Representatives. This time, however, when the results load in the iframe, this script will call the parent function showReps(doc) :

<script>
 // - this is the script in the iframe results page
 parent.showReps(document);
</script>

The showReps(doc) function in the parent (this page) uses the document reference to retrieve the table in the iframe and put it into div id="results2". The script looks like this:

<script>
 // - this is the script in this page
function showReps(doc){
 var x = doc.getElementById('state_reps').innerHTML;
 document.getElementById('results2').innerHTML = x;
}
</script>

Method 3

Method 3 uses the onload event handler to gain access to the document object of iframe name="repIframe3" source page using window.frames['repIframe3'].document.

This method will NOT work with Netscape 6.

Here's how this example works: place the event handler onload="getIframeDoc()" in the iframe tag. Next, choose a State from the select object in form name="list3". When the page loads in the iframe it will exectue the getIframeDoc function.

<iframe name="repIframe3" src="blank.html" onload="getIframeDoc()"></iframe>

<script>
 function getIframeDoc(){
  var iframeDoc = window.frames['repIframe3'].document;
  var sr = iframeDoc.getElementById('state_reps');
  if (sr){
   var reps3 = sr.innerHTML;
   document.getElementById('results3').innerHTML = reps3;
   }
 }
</script>

Oct 23, 2012

Custom validator with Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UsingCustomValidator" %>

<!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>Using a CustomValidator</title>
</head>
<body>
    <form id="form1" runat="server">
   
    Enter a date:<br />
    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="custDate" runat="server"
       ControlToValidate="txtDate"
       ValidateEmptyText="false" 
       Text="Enter a valid future date"
       OnServerValidate="custDate_ServerValidate" />  
   

   <script type="text/javascript">
     function validateOrFields(source, args){
       var sUser = document.form1.<%= txtUser.ClientID %>.value;
       var sEmail = document.form1.<%= txtEmail.ClientID %>.value;
      
       if (sUser == "" && sEmail == "")
       {
          args.IsValid = false;
       }
       else
       {
          args.IsValid = true;
       } 
       return; 
     }
   </script>
  
   Enter user name:<br />
   <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
   <br />
   Enter email:<br />
   <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

   <asp:CustomValidator ID="OrFieldValidator"
                        runat="server"
                        Text="Enter either a user name or a email"
                        ClientValidationFunction="validateOrFields"
                        OnServerValidate="OrFieldValidator_ServerValidate" />  
  

  
   <asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server" />
  
   </form>
</body>
</html>
<script type="text/javascript">
  ValidatorHookupControlID("<%= txtUser.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
  ValidatorHookupControlID("<%= txtEmail.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
</script>
 File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UsingCustomValidator : System.Web.UI.Page
{
   protected void custDate_ServerValidate(object source, ServerValidateEventArgs args)
   {
      string sEnteredDate = args.Value;
      DateTime dt;
      bool convertSuccessful = DateTime.TryParse(sEnteredDate, out dt);
      if (convertSuccessful && dt >= DateTime.Today)
         args.IsValid = true;
      else
         args.IsValid = false;
   }

   protected void OrFieldValidator_ServerValidate(object source, ServerValidateEventArgs args)
   {
      if (txtUser.Text.Length <= 0 && txtEmail.Text.Length <= 0)
         args.IsValid = false;
      else
         args.IsValid = true;
   }
}

Postback With Javascript

Entire form tag of the asp.net page

<form id="form1" runat="server">
    <asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>

    <input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
    <input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />

    <asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
    <asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>

Entire Contents of the Page's Code-Behind Class

Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
    Response.Write("You ran the ButtonA click event")
End Sub

Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
    Response.Write("You ran the ButtonB click event")
End Sub
The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed

What's going on?

Two input controls are rendered to the client:

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />

    __EVENTTARGET receives argument 1 of __doPostBack
    __EVENTARGUMENT receives argument 2 of __doPostBack

The __doPostBack function is rendered out like this:


function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
As you can see, it assigns the values to the hidden inputs.

When the form submits / postback occurs:

If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.

What if I don't want to run a click handler, but want to do something else instead?

You can pass whatever you want as arguments to __doPostBack

You can then analyze the hidden input values and run specific code accordingly:

If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
    Response.Write("Do Something else")
End If
another Solution
<script type="text/javascript">
     <!--
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');
         }
     -->
</script>

Aug 30, 2012

ASP.Net Repeater dynamically using C# code

ASP.Net Repeater Databound Control can be generated dynamically using C# code. You can render the data items in dynamically generated Repeater Control. ASP.Net Panel Control can be used to add Repeater Control dynamically inside it as a child control. Method of database connectivity and Databinding using DataSource object of Repeater Control is same as we discussed in the previous article about ASP.Net Repeater Control Databinding using DataSource. While creating a dynamic Repeater control, you also have to generate its ItemTemplate, SeparatorTemplate and HeaderTemplate dynamically to display the data items retrieved from the database. In C# code behind use the DataSource object to bind the data with dynamic Repeater Control and add it as a child control of ASP.Net Panel to render all stuff on the web page.

HTML Code to Generate ASP.Net Repeater Control Dynamically

<asp:Panel ID="Panel1" runat="server">  
</asp:Panel> 

C# Code to Generate ASP.Net Repeater Control Dynamically


// Repeater Control Databinding using Datasource  
Repeater Repeater1 = new Repeater();  
Repeater1.DataSource = myDataSet;  
Repeater1.DataBind();  
  
foreach (RepeaterItem repeatItem in Repeater1.Items)  
{  
    // if condition to add HeaderTemplate Dynamically only Once  
    if (repeatItem.ItemIndex == 0)  
    {  
        RepeaterItem headerItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Header);  
        HtmlGenericControl hTag = new HtmlGenericControl("h4");  
        hTag.InnerHtml = "Employee Names";  
        repeatItem.Controls.Add(hTag);  
    }  
  
    // Add ItemTemplate DataItems Dynamically  
    RepeaterItem repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Item);  
    Label lbl = new Label();  
    lbl.Text = string.Format("{0} {1} <br />", myDataSet.Tables[0].Rows[ repeatItem.ItemIndex ]

    [ "FirstName" ], myDataSet.Tables[0].Rows[ repeatItem.ItemIndex ][ "LastName" ]);  
    repeatItem.Controls.Add(lbl);  
  
    // Add SeparatorTemplate Dynamically  
    repeaterItem = new RepeaterItem(repeatItem.ItemIndex, ListItemType.Separator);  
    LiteralControl ltrlHR = new LiteralControl();  
    ltrlHR.Text = "<hr />";  
    repeatItem.Controls.Add(ltrlHR);  
}  
  
// Add Repeater Control as Child Control  
// of Panel Control  
Panel1.Controls.Add(Repeater1);


Aug 28, 2012

General Page Life-Cycle Stages

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering.


In general terms, the page goes through the stages outlined in the following :

1 Page request   : The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
 

2 Start :  In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

3  Initialization : During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
4  Load : During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

5  Validation : During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

6 Postback event handling  : if the request is a postback, any event handlers are called.

 7 Rendering : Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

8  Unload :  Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Aug 26, 2012

Hide a Parent Node

I have a TreeView and SiteMapDatasource on my .aspx page. Web.config has siteMapProvider settings and a SiteMap file (Web.sitemap). 

.aspx file:
<asp:TreeView ID="TreeView1" runat="server" AutoGenerateDataBindings="False" DataSourceID="SiteMapDataSource1" ontreenodedatabound="TreeView1_TreeNodeDataBound">
</asp:TreeView>
<br />
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
Above is .aspx file with controls for this example. You should note we have a event handler for OnTreeNodeDataBound event of TreeView.
Web.config:
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true"> <providers> <add name="XmlSiteMapProvider" type="System.Web.XmlSiteMapProvider"
siteMapFile="Web.siteMap" securityTrimmingEnabled="true"/> </providers> </siteMap>
Part of web.config is shown above with SiteMapProvider. Note we have siteMapFile="Web.sitemap"  and securityTrimmingEnabled="true" for Roles to be applied to the sitemap.
Web.SiteMap:
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="~/Default.aspx" title="Home" description="Home">
<siteMapNode url="~/Level1.aspx" title="Level 1" description="" > <siteMapNode url="~/Page1.aspx" title="Page1" description="" />
<siteMapNode url="~/Page2.aspx" title="Page2" description="" /> </siteMapNode>
<siteMapNode url="~/NoChilde.aspx" title="Level 2" description="" /> <siteMapNode url="~/Level3.aspx" title="Level 3" description="" >
<siteMapNode url="~/Page3.aspx" title="Page3" description="" /> </siteMapNode>
</siteMapNode> </siteMap>
The above sitemap is not very realistic looking but will serve the purpose for our demonstration. We see that siteMapNode "Level 2" does not have any childnode. So we want to hide it and not show in our TreeView. In real case scenario it might have few child nodes with Roles attribute set. If user is not in particular role the SiteMapProvider will hide those node.
Without the code-behind which we are going to see in a moment the TreeView will look like below:



We now want to hide "Level 2" node as it does not have any child node.

.aspx.cs file (code-behind):
protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e) {
SiteMapNode node = (SiteMapNode)e.Node.DataItem;
if(node.HasChildNodes ==false && e.Node.Depth ==1) {
TreeView1.Nodes[0].ChildNodes.Remove(e.Node);

}
}
In the above code what we are doing is first getting the DataItem for the CurrentNode that is being DataBound. For this we have to use SiteMapNode.
1: we check if the node has Child with node.HasChildNodes ==false.
2: "Home" is at Depth 0 while Level 1,2 and 3 are at Depth 1 and Page1,Page2 and so on are at Depth=2. So to make sure that we are not hiding Home or any leaf nodes (page1,Page2 etc) we are checking that depth of current Node is 1.
If the above two conditions are met then we will remove the current node (i.e. e.Node) from TreeView1.
For this we first get the NodesCollection for TreeView1. i.e. TreeView1.Nodes[0], Here 0 is because we have all Nodes under "Home" parent Node.
After that we call the ChildNodes.Remove method to remove the current Node.
That is it. Now if we run the code we will get the following output for TreeView:





ShowStartingNode=False set for SiteMapDataSource:

 If you set the ShowStartingNode=False for SiteMapDataSource then you might want to chage the Depth=0 and also make little change on how to remove node.
The code should look like below:

protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e) {
SiteMapNode node = (SiteMapNode)e.Node.DataItem;
if(node.HasChildNodes ==false && e.Node.Depth ==0) {
TreeView1.Nodes.Remove(e.Node);
}
}
Thats it. Thanks for reading this article.

Improve reference efficiency in JavaScript files inside a web project

In Visual Studio 2010 you can reference other JavaScript files inside current JavaScript file like the following, to get the IntelliSense.

/// <reference path="YourScript.js" />

What if you have many JavaScript files and you have to reference many project wide JavaScript files inside each file?  You can put the following block in each of the JavaScript files that need the reference like following:

/// <reference path="YourScript1.js" />
/// <reference path="YourScript2.js" />
/// <reference path="YourScript3.js" />
/// <reference path="YourScript4.js" />


But this would not be efficient especially some referencing file name is going to change, such as when JQuery library version changes.  The trick is to create a project wide reference JavaScript file, and explicitly reference this file from other JavaScript files.  For example, we can create a file called reference.js which contains the above code.  Then for other JavaScript files, we can reference it by dragging and drop the reference.js file into the JavaScript editor, which will generate the following:

/// <reference path="Scripts/AppJsReference.js" />

Basically, Visual Studio 2010 recursively check the references included in the referenced JavaScript files to find the current JavaScript file's references.  I hope this can ease some pain in the development.
Related Posts Plugin for WordPress, Blogger...