IronPython for ASP.NET CTP版發布的訊息無疑讓人激動,我也迫不及待的下載下來體驗一下,根據提供的入門教程寫一個最基本的Web頁面。在開始之前,你需要下載安裝IronPython for ASP.NET CTP版。
1.開啟VS2005,建立Web網站,並選擇語言為IronPython。
2.切換Default.aspx頁面到設計模式,在表單上拖放一個TextBox、Button、Label控制項。
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button"/>
<h3><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></h3>
</div>
3.切換到代碼檔案(Default.aspx.py),可以看到已經匯入了一些常用的命名空間
import System
from System.Data import *
from System.Web import *
from System.Web.UI import *
from clr import *
同時還有一個表單載入事件:
def Page_Load():
if not IsPostBack:
pass
這裡的pass只是一個預留位置而已,並沒有什麼實際的意義。
4.編寫表單載入事件代碼,在表單載入時我們顯示自己的使用者名稱:
def Page_Load():
if not IsPostBack:
Label1.Text = "TerryLee"
5.編寫Button1的單擊事件代碼:
def Button1_Click(sender, args):
Label1.Text = Textbox1.Text
注意這裡代碼都要手工輸入,不能通過在表單中雙擊按鈕或者是在屬性視窗選擇相關事件。
6.在HTML代碼中,為Button1加上Click事件,完成後代碼如下:
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br /><br />
<h3><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></h3>
</div>
7.激動人心時刻來臨,一個很“複雜”的基於IronPython的ASP.NET Web頁面終於完成了,運行後介面如下:
文字框中輸入cnblogs後單擊按鈕:
8.如果不想使用獨立的代碼檔案,在ASPX頁面中的代碼如下:
<script runat="server">
def Page_Load():
if not IsPostBack:
Label1.Text = "TerryLee"
def Button1_Click(sender, args):
Label1.Text = Textbox1.Text
</script>
使用IronPython建立簡單的Web頁面就體驗到這兒,後面再繼續體驗其他幾個入門教程。
註:該例子來自於IronPython入門教程。