Pages

Free Hosting
Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Monday, October 17, 2011

Accessing and Displaying Data with JScript .NET in ASP.NET


In this section, you create a simple page that uses the DataGrid control. This page will serve as the basis for the pages in subsequent sections.
To create a simple ASP.NET page with a DataGrid control
  1. In your Web directory, located at C:\Inetpub\wwwroot by default, create a new directory named DataAccess.
  2. Create a new ASP.NET file named DataAccess.aspx in the C:\Inetpub\wwwroot\DataAccess directory.
You can do this with an application such as Notepad.
Note   You cannot use the Visual Studio .NET integrated development environment (IDE) to create a JScript .NET project. However, you can edit ASP.NET files in the IDE.
  1. Open the ASP.NET page for editing in either the Visual Studio .NET IDE or Notepad.
Note   You cannot directly paste code copied from a richly formatted source (such as a Web page) into an ASP.NET page that you are editing in the Visual Studio .NET IDE. The IDE converts richly formatted text into HTML code that reproduces the look of the original text instead of pasting as unformatted text. You can use a two-step process to work around this restriction. First, paste a code example into a text-based editor (such as Notepad) to remove the rich formatting. Second, cut the code from the text-based editor and paste it into the IDE.
  1. Add the following code to the page:
<%@ Page Language=jscript %>
<html>
<body>
<script runat=server>
function Page_Load(sender : Object, e : EventArgs) {
// Put code in this function that you want to have loaded
// each time the page is requested from the server.
if (!IsPostBack) {
// Put code here that you want to run only the first time.
}
// Page_Load
</script>
<h3>Category List</h3>
<form runat=server>
<asp:DataGrid id="ItemsGrid" runat="server">
</asp:DataGrid>
</form>
</body>
</html>
  1. Save the page.
  2. View the page by typing the following address into the address bar of Internet Explorer:
http://localhost/DataAccess/DataAccess.aspx
When you access the page, it only displays the "Category List" header. The DataGrid control does not display data because no data has been bound to it.
Creating and Displaying a DataTable
Before you attempt to load data from a database, ensure that the DataGrid control works properly by using data from a well-controlled data source. In this section, you construct an ArrayList, and then you bind the ArrayList to the DataGrid control.
To bind data to a DataGrid control
  1. Add the following function to the script block.
function CreateTestData() : ICollection {
// Function to create a simple table.
var al : ArrayList = new ArrayList();
al.Add("orange");
al.Add("pear");
al.Add("banana");
return al;
} // CreateTestData
  1. Bind the data in the table to the DataGrid control by adding the following lines to the if (!IsPostBack) block of the Page_Load function:
ItemsGrid.DataSource = CreateTestData();
ItemsGrid.DataBind();
  1. Save the page.
  2. Reload the page in Internet Explorer, or type the following address in the address bar of Internet Explorer:
http://localhost/DataAccess/DataAccess.aspx
The page now displays a simple table of several fruits.

Calling JavaScript from ASP.NET Master Page and Content Pages


You can call an existing JavaScript function from a Master Page or can create one on the fly. Here are some common scenarios:
1. Create a JavaScript function on the fly and call the JavaScript function in the MasterPage Page_Load() event
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        string someScript = "";
        someScript = "<script language='javascript'>alert('Called from CodeBehind');</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", someScript);
    }
VB.NET
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim someScript As String = ""
        someScript = "<script language='javascript'>alert('Called from CodeBehind');</script>"
        Page.ClientScript.RegisterStartupScript(Me.GetType(), "onload", someScript)
    End Sub

The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind.


2. Call an existing JavaScript function on MasterPage Page_Load() event
Let us assume you have an existing JavaScript function declared in between the <head> tags, then here’s how to call that function from Page_Load()
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function invokeMeMaster() {
            alert('I was invoked from Master');
        }
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.ClientScript.IsStartupScriptRegistered("alert"))
        {
            Page.ClientScript.RegisterStartupScript
                (this.GetType(), "alert", "invokeMeMaster();", true);
        }

    }

3. Call JavaScript function from MasterPage on Button click
If you want to call a JavaScript function on a Button click, then here’s how to do so:
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function invokeMeMaster() {
            alert('I was invoked from Masterdotnetcurry');
        }
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
In the <body> tag, add a Button and use the OnClientClick to call this function
<asp:Button ID="btnMaster" runat="server" Text="Button" OnClientClick="return invokeMeMaster();"/>

The OnClientClick() is called before the postback occurs. This gives us a place to check for some condition and cancel the submit if the condition is not satisfied.


4. Access a control on the MasterPage using JavaScript
If you have a control on the MasterPage and need to access it using JavaScript, then here’s how to do so. In this sample, we will test the length of the TextBox to see if there are 5 or more letters. If the number of letters is less than 5, the form submit will be cancelled.
Add a TextBox and a Button control in the MasterPage (outside the ContentPlaceHolder) as shown below
<body>
    <form id="form1" runat="server">
    <div>
       <asp:Panel ID="panelMaster" GroupingText="MasterPage controls" runat="server">      
            <asp:TextBox ID="txtMaster" runat="server"></asp:TextBox>
            <asp:Button ID="btnMaster" runat="server" Text="Button" OnClientClick="return accessMasterControl();" />
            <br />
        </asp:Panel>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
       
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
In the <head> element of the MasterPage, add the following code:
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function accessMasterControl() {
            if (document.getElementById('<%=txtMaster.ClientID%>').value.length <= 5) {
                alert('Minimum 5 characters required')
                return false;
            }
            else { return true;}
        }
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
5. Access a control on the Content Page from a MasterPage using JavaScript
If you have a control on the Content Page which has to be accessed in the MasterPage using JavaScript, then here’s how to do so:
On the Content Page, create a TextBox as shown below :
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Panel ID="panelContent" GroupingText="ContentPage Controls" runat="server">
        <asp:TextBox ID="txtContent" runat="server"></asp:TextBox>
    </asp:Panel>
</asp:Content>

Now access and populate the TextBox ‘txtContent’ from the MasterPage
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function accessControlContentPage() {
var txtCont = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("txtContent").ClientID %>');
    txtCont.value = "I got populated using Master Page";               
}
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
6. Ask user before submitting the form on a MasterPage
In order to ask the user for a confirmation before submitting the form, you can either use code behind or can use simple mark up as shown below:
Declare a Button control that causes postback and write the following code in MasterPage.master.cs 
C#
protected void Page_Load(object sender, EventArgs e)
{
    string myScript = @"<script type='text/javascript'>
    function askBeforeSubmit() {
    var msg = 'Are you sure?';
    return confirm(msg);
    }
    </script>";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MakeSure", myScript);
    form1.Attributes.Add("onsubmit", "return askBeforeSubmit();");
}

If you want to avoid a code-behind approach, you can ask the user for a confirmation by using the OnClientClick() on the Submit button
<asp:Button ID="btnMaster" runat="server" Text="Button"
OnClientClick="return confirm('Are you sure?');"/>