IronPython入門教程第二篇使用共用代碼,建立一個簡單的IronPython類,並在ASP.NET頁面中使用它。
1.建立Web網站和ASP.NET頁面,選擇語言為IronPython。
2.關於App_Script檔案夾。經過上面第一步操作後,建立Web網站中會自動建立一個名為App_Script的檔案夾,在這裡你可以添加一些可重用的IronPython共用類,在該檔案夾下只可以放類,而不能放其它諸如Web Page,User Control等檔案。
3.建立一個簡單的共用類。在App_Script檔案夾中添加新項,會彈出如下對話方塊,選擇IronPython Module。
建立一個簡單的共用類SampleClass,在該類中有一個屬性TestString,它通過property()函數來指定它的存取方法SetTestString()和GetTestString(),代碼如下:
class SampleClass:
"Sample class with one property"
_testString = ""
def SetTestString(value):
_testString = value
def GetTestString():
return _testString
TestString = property(GetTestString, SetTestString)
4.使用共用類,在ASP.NET頁面中添加相關的控制項,如下所示:
<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>
開啟Default.aspx.py檔案,匯入命名空間:
import SampleModule
from SampleModule import SampleClass
編寫按鈕的單擊事件:
def Button1_Click(sender, args):
sc = SampleClass()
sc.TestString = TextBox1.Text
Label1.Text = sc.TestString
運行後在文字框中輸入TerryLee,單擊按鈕如下:
完整範例程式碼下載:http://files.cnblogs.com/Terrylee/IronPythonDemo2.rar
註:該例子來自於IronPython 入門教程。