Insus.NET在MasterPage放置了一个DropDownList和一个Button控件,然后在Default.aspx放置一个TextBox。从上面的动画中可以看到,在TextBox输入文字,它会动态添加至MasterPage的DropDownList控件中。
实现过程,首先写一个接口:
IGetable using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for IGetable
/// </summary>
namespace Insus.NET
{
public interface IGetable
{
string TextBoxValue
{
get;
}
}
}
接下来,新建MasterPage:
InsusMasterPage.master:
InsusMasterPage.master <%@ Master Language="C#" AutoEventWireup="true" CodeFile="InsusMasterPage.master.cs" Inherits="InsusMasterPage" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" Width="100">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Add Item" OnClick="Button1_Click" />
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
InsusMasterPage.master.cs代码,重点部分已经有注释,难度应该不大:
InsusMasterPage.master.cs using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class InsusMasterPage : System.Web.UI.MasterPage
{
//Insus.NET:宣告一个泛型,将存储输入的数据
List<string> list = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Data_Binding();
}
}
private void Data_Binding()
{
this.DropDownList1.DataSource = list;
this.DropDownList1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
//Insus.NET:把page转为接口,并取属性
string v = ((IGetable)this.Page).TextBoxValue;
//Insus.NET:判断Session是否为空
if (Session["db"] != null)
{
//Insus.NET:如果不为空,直接从Session取出
list = (List<string>)Session["db"];
}
else
{
//Insus.NET:如果为空,new一个实例
list = new List<string>();
}
//Insus.NET:把输入值加入泛型
list.Add(v);
//Insus.NET:存入Session
Session["db"] = list;
Data_Binding();
}
}
最后,是Aspx的代码:
Default.aspx:
View Code <%@ Page Title="" Language="C#" MasterPageFile="~/InsusMasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Content>
Default.aspx.cs:
View Code using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public partial class _Default : System.Web.UI.Page,IGetable
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Insus.NET:实现接口
public string TextBoxValue
{
get {
return this.TextBox1.Text;
}
}
}
好了,非常简单的例子。