ASPX

From no name for this wiki
Revision as of 13:10, 7 September 2009 by Claude (talk | contribs) (The bin folder)
Jump to: navigation, search

ASPX Samples

Ein Hello World

Mono:

  • 1. Inhalt in eine Datei mit dem Namen HelloWorld.aspx kopieren.
  • 2. xsp2 im Verzeichnis aufstarten, wo sich diese Datei befindet.
  • 3. Folgende URL im Browser eingeben: http://127.0.0.1:8080/HelloWorld.aspx
<%@ Page Language="C#" AutoEventWireup="true"  %>
<!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">

<script language="C#" runat="server">

    
    
 void ButtonClicked(Object Src, EventArgs E) {
     this.submitbutton.BackColor = System.Drawing.Color.Red;
     this.labelMessage.Text = this.text.Text;
     this.labelMessage.ForeColor = System.Drawing.Color.Pink;           
 }

</script>


<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    
    <asp:Label ID="labelMessage" runat="server" Text="Label"></asp:Label>        
    <hr />
    <asp:Label ID="labelInsertText" runat="server" Text="Write a Text:"></asp:Label>
    <asp:TextBox ID="text" runat="server"></asp:TextBox>
    <asp:Button ID="submitbutton" runat="server" Text="Press me" OnClick="ButtonClicked" />
    </form>
</body>
</html>

Request Parameter auslesen

Bei einer URL http://localhost:49622/HelloWorld/HelloWorld.aspx?myparam=Hehe wuerde das Label den Text Hehe bekommen.

<script language="C#" runat="server">

 void Page_Load(Object Sender, EventArgs e)
 {    
       this.labelMessage.Text = Request.QueryString["myparam"];        
 }

</script>

Doku fuer Request siehe HttpRequest

Namespaces importieren

Am Anfang der Datei:

<%@ Page Language="C#" %>
<%@ import Namespace="System.Threading" %>
<%@ import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

</script>
<html></html>


Code behind

Code in separate Dateien auslagern. Die Klasse muss eine partielle Klasse sein und von Page erben:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        this.Button1.BackColor = Color.Red;
        string text = this.Category.Text;
        Console.WriteLine(text);
    }
}

In der ASPX Seite folgende Direktive einfuegen. In dem Inhertis Attribut wird der Klassenname angegeben.

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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
           Name: 

           Category:  <asp:dropdownlist id="Category" runat=server>
                         <asp:listitem >psychology</asp:listitem>
                         <asp:listitem >business</asp:listitem>
                         <asp:listitem >popular_comp</asp:listitem>
                      </asp:dropdownlist>        

           <asp:textbox id="Name" runat="server"/>

      

           <asp:button ID="Button1" text="Lookup" runat="server" onclick="Button1_Click"/>


    </form>
</body>
</html>

Scriptlets und server side comment

Scriptlets, wie in JSPs:

<html>
<body>

<%-- Thats a comment --%>

<% for(int i=0; i<10;i++){ %>
  Hello World
  <hr/>
<% } %>
</body>
</html>

Expression syntax

<%$ expression here %>


Beispiel:

<% for (int i=0; i<8; i++) { %>
     <font size="<%=i%>"> Hello World! </font> <br>
<% } %>

Scopes

Validierung

hello world

<tr>
      <td align=left>Name:</td>
      <td>
        <asp:TextBox id=txtName runat="server" />
      </td>
      <td>
        <asp:RequiredFieldValidator id="ReqFName" runat="server"
            ControlToValidate="txtName" 
            ErrorMessage="Bitte Name eingeben!">
        </asp:RequiredFieldValidator>
      </td>
 </tr>

Masterpages

Die Masterpage (MasterPage.master):

<%@ Master Language="C#" AutoEventWireup="true" %>

<!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>Masterpage</title>  
</head>
<body>
    <div style="background:yellow">
        This is content on the master page
    </div>
    <form id="form1" runat="server">
    <div style="background: blue" >
        <asp:ContentPlaceHolder id="MainContent" runat="server">
        
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>


Die Contentpage (Default2.aspx):

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"  Title="Untitled Page" %>

<asp:Content ID="mycontent" ContentPlaceHolderID="MainContent" Runat="Server">
This is my content.
</asp:Content>


The bin folder

Assemblies können im mywebapp/bin plaziert werden.

IHTTPHandler

HTTP Handlers sind analog zu Javas Servlets. Die Datei mit dem Sourcecode sollte im App_Code Verzeichnis abgelegt sein:

Der Code:

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

/// <summary>
/// Summary description for HttpHandlers
/// </summary>
public class MyHandler : IHttpHandler
{
    
      public void ProcessRequest(HttpContext context)
      {
         context.Response.Write("<H1>This is an HttpHandler Test.</H1>");      
         context.Response.Write("<p>Your Browser:</p>");
         context.Response.Write("Type: " + context.Request.Browser.Type + "<br>");
         context.Response.Write("Version: " + context.Request.Browser.Version);
      }

      
      public bool IsReusable
      {
         get { return true; }
      }
		
	
}


In der Konfiguration:

<httpHandlers>
     <add verb="*" path="myhandler.aspx" type="MyHandler"/>
</httpHandlers>

Doku: ihttphandler

IHttpModule

Ein Http Modul ist analog zu Javas ServletFilter. Im Verzeichnis App_Code in einer Datei blabal.cs

public class HelloWorldModule : IHttpModule
{
    public HelloWorldModule()
    {

    }

    public String ModuleName
    {
        get { return "HelloWorldModule"; }
    }

    // In the Init function, register for HttpApplication 
    // events by adding your handlers.
    public void Init(HttpApplication application)
    {
        application.BeginRequest +=
            (new EventHandler(this.Application_BeginRequest));
        application.EndRequest +=
            (new EventHandler(this.Application_EndRequest));
    }

    private void Application_BeginRequest(Object source,
         EventArgs e)
    {
        // Create HttpApplication and HttpContext objects to access
        // request and response properties.
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        string filePath = context.Request.FilePath;
        string fileExtension =
            VirtualPathUtility.GetExtension(filePath);
        if (fileExtension.Equals(".aspx"))
        {
            context.Response.Write("<h1><font color=red>" +
                "HelloWorldModule: Beginning of Request" +
                "</font></h1><hr>");
        }
    }

    private void Application_EndRequest(Object source, EventArgs e)
    {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        string filePath = context.Request.FilePath;
        string fileExtension =
            VirtualPathUtility.GetExtension(filePath);
        if (fileExtension.Equals(".aspx"))
        {
            context.Response.Write("<hr><h1><font color=red>" +
                "HelloWorldModule: End of Request</font></h1>");
        }
    }

    public void Dispose() { }
}

In der web.config Datei:

 <httpModules>
   <add name="HelloWorldModule" type="HelloWorldModule"/>      
 </httpModules>

Custom Membership Provider

Life Cycle einer ASPX Page

  • 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.
  • Start: In the start step, 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. Additionally, during the start step, the page's UICulture property is set.
  • Page initialization: During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. 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.
  • Load: During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
  • 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.
  • Postback event handling: If the request is a postback, any event handlers are called.
  • 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.
  • 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.

Resourcen