ASPX

From no name for this wiki
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>
 
<%-- That's 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>

Databinding

hello World mit einer DrowDown Liste

In der PageLoad Methode:

    protected void Page_Load(object sender, EventArgs e)
    {
 
      //Paragaph
      DataTable paragraphTable = QuestionManagement.Instance.GetParagraphIdAndTitleByTestId(1);
      this.DropDownListParagraph.DataSource = paragraphTable;  
      this.DropDownListParagraph.DataTextField = "TITLE";
      this.DropDownListParagraph.DataValueField = "ID";
      this.DropDownListParagraph.DataBind();
 
    }

Aspx:

   <!-- Paragraph -->
   <asp:Label ID="LabelParagraph" runat="server" Text="Paragraph:"/>
   <asp:DropDownList ID="DropDownListParagraph" runat="server"/>
   <br/>

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

Custom Role Provider und Page Access

Der Code

Sehr einfacher RoleProvider mit nur zwei Rollen. User mit dem Namen admin hat Rolle admin und user, alle anderen haben die Rolle user.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Configuration.Provider;
 
 
namespace CustomRoleProvider
{
 
    public sealed class TestmasterRoleProvider : RoleProvider
    {
        string applicationName;
 
        public override string ApplicationName
        {
            get { return this.applicationName; }
            set { this.applicationName = value; }
        }
 
        public override bool IsUserInRole(string username, string rolename)
        {
            //Der User Admin hat alle Rollen
            if (username.Equals("admin"))
            {
                return true;
            }
 
            //Alle anderen haben die Rolle user
            if (rolename.Equals("user"))
            {
                return true;
            }
            return false;
        }
 
        public override string[] GetRolesForUser(string username)
        {
            //Der Admin hat die Rolle admin und user
            if (username.Equals("admin"))
            {
                return new string[] { "admin", "user" };
            }
            //Alle anderen haben nur die Rolle user
            return new string[] { "user" };
 
        }
 
        public override void CreateRole(string rolename)
        {
            throw new Exception("not supported");
        }
 
        public override bool DeleteRole(string rolename, bool throwOnPopulatedRole)
        {
            throw new Exception("not supported");
        }
 
        public override string[] GetAllRoles()
        {
            return new string[] { "admin", "user" };
 
        }
 
        public override string[] GetUsersInRole(string rolename)
        {
            throw new Exception("not supported");
        }
 
        public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames)
        {
            throw new Exception("not supported");
 
        }
 
        public override bool RoleExists(string rolename)
        {
            throw new Exception("not supported");
        }
 
        public override string[] FindUsersInRole(string rolename, string usernameToMatch)
        {
            throw new Exception("not supported");
        }
 
        public override void AddUsersToRoles(string[] usernames, string[] rolenames)
        {
            throw new Exception("not supported");
        }
    }
}

Die Hauptkonfiguration

Die Haupt web.config Datei (Root Verzeichnisss).

<?xml version="1.0"?>
<configuration>
	<system.web>
 
         <roleManager enabled="true" defaultProvider="TestmasterRoleProvider" >
	   <providers>
             <clear />
             <add name="TestmasterRoleProvider"  type="Testmaster.Login.TestmasterRoleProvider"         
               applicationName="Testmaster"/>
              </providers>
         </roleManager>
 
 
    	<authentication mode="Forms">    	         
      	  <forms loginUrl="default.aspx"/> 	                   
        </authentication>
 
	<membership defaultProvider="TestmasterMembershipProvider">
 	  <providers>
  	    <clear/>
   	    <add name="TestmasterMembershipProvider" type="Testmaster.Login.MyProvider"/>
	  </providers>
	</membership>      
 
	</system.web> 
</configuration>

Konfigurationsdateien pro gesichertes Unterverzeichnis

  •  ? bedeutet anonymer Benutzer
  • * bedeutet alle Benutzer.

Anbei ein brauchbares web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <authorization>  
            <allow roles="admin"/> 
            <deny roles="user"/>         
            <deny users="?" />                              
        </authorization>
    </system.web>
</configuration>

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.

Custom User Control

WebUserControl.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
Hello from custom control.
Hello message: <asp:Label ID="Label" runat="server"/>

WebUserControl.ascx.cs

using System;
using System.Collections;
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;
 
public partial class WebUserControl : System.Web.UI.UserControl
{
 
    private string helloText;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Label.Text = HelloText;
    }
 
    public string HelloText
    {
        get
        {
            return this.helloText;
        }
        set
        {
            this.helloText = value;
        }
    }
}

Client.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/WebUserControl.ascx" TagPrefix="uc" TagName="WebUserControl"%>
<!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">
    <div>
        <uc:WebUserControl ID="MycustomControl" HelloText="MyHelloText" runat="server"/>
    </div>
    </form>
</body>
</html>

Custom Control

Source Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WikiText
{
    public class WikiTextBox : WebControl
    {
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.Write("Hello World!");
        }
    }   
}

Das dll ins Bin Verzeichnis der Webapplikation kopieren.

Ein Client kann wie folgt aussehen:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="uc" Namespace="WikiText" Assembly="WikiText"%>
<!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">
    <div>
        <uc:WikiTextBox runat="server" />
    </div>
    </form>
</body>
</html>

GridView Sample

Füllen des GridView Controls mit Daten:

DataTable questions = QuestionManagement.Instance.GetQuestionsByUserId(userid);
GridViewSuccessfulTests.DataSource = questions;
GridViewSuccessfulTests.DataBind();

Das GridView Control in Action:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="myquestions.aspx.cs" Inherits="MyQuestions" MasterPageFile="../masterpage.master" %>
<asp:Content ID="contentX0015" ContentPlaceHolderID="pagecontent" Runat="Server">
 
<div class="post">
   <h2 class="title">Meine Fragen</h2>                          
</div>
 
 <asp:GridView ID="GridViewSuccessfulTests" runat="server" AutoGenerateColumns="False">
 
  <HeaderStyle BackColor="#aaaadd"/>
 
  <Columns>
 
    <asp:BoundField ReadOnly="true" HeaderText="Id" DataField="ID"/>
    <asp:BoundField ReadOnly="true" HeaderText="Titel" DataField="TITLE"/>
    <asp:BoundField ReadOnly="true" HeaderText="Test" DataField="TEST_TITLE"/>
    <asp:BoundField ReadOnly="true" HeaderText="Paragraph" DataField="P_TITLE"/>
    <asp:TemplateField HeaderText="Ansehen">
       <ItemTemplate>
         <a href="/secured/editquestion.aspx?questionid=<%# string.Format("{0}", Eval("ID"))%>">Bearbeiten</a>         
       </ItemTemplate>
    </asp:TemplateField>
 
  </Columns> 
 
 </asp:GridView>  
</asp:Content>

Repeater und GridView

Resourcen