AdolphYang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1  aspx的语法介绍:

    web窗体有三个文件,WebForm_Add.aspx类似html页面,WebForm_Add.aspx.c是触发的事件,WebForm_Add.aspx.designer.cs是控件元素的声明。

    web窗体中局部变量可以声明在.aspx中,成员变量可以声明在.aspx.cs中。

    .aspx中可以用<% %>写C#代码,可以用<%=name %> 和<%Response.Write(name); %>进行变量输出。

   <div>
        <%=name %><br />
        <% var age = 18; %>
        <%=age %><br />
        <ul>
            <%
                for (var i = 0; i < 10;i++ )
                {
            %>
                    <li><%=i %></li>
                    <li><%Response.Write( i+1); %></li>
                    <li><%Response.Write(age + i); %></li>
            <%
                }
            %>
        </ul>
    </div>

<!-- name声明在了.aspx.cs中,至少是protected级别 -->
WebForm_Add.aspx

 2  .aspx与.aspx.cs的关系:

    .aspx.cs与.aspx.designer.cs是部分类,是同一个类WebForm_Add.cs,继承了IHttpHandler,

    同时有一个动态类.day5_webform_add_aspx.cs 继承WebForm_Add.cs,

    而day5_webform_add_aspx.cs 通过反编译可以看到它对 .aspx进行了字符串的替换和拼接,最终输出了html。

    如果父类WebForm_Add.cs有private字段,则子类day5_webform_add_aspx.cs 无法继承,也就无法用来替换.aspx 中的变量(被‘《%’标记的字符串)。

    总之,.aspx只是一个准备被替换和处理的模板,.aspx.cs和.aspx.designer.cs 是同一个类 WebForm_Add.cs,有一个动态的子类day5_webform_add_aspx.cs继承它。这个子类才是真正从事IHttpHandler的工作,进行替换和拼接,并最终生成html的类。

 public partial class WebForm_Add : System.Web.UI.Page
    {
        protected string name = "茹鹏伟";
        
        protected void Page_Load(object sender, EventArgs e)
        {
            Context.Response.Write(this.GetType() + "<br/>");
            Context.Response.Write(this.GetType().Assembly.Location + "<br/>");
            Context.Response.Write(this.GetType().BaseType + "<br/>");
            Context.Response.Write(this.GetType().BaseType.Assembly.Location + "<br/>");
        }
    }
WebForm_Add --> 来自文件WebForm_Add.aspx.cs

输出结果是:

ASP.day5_webform_add_aspx
C:\Users\yangguo\AppData\Local\Temp\Temporary ASP.NET Files\vs\758cfd64\1e0a1365\App_Web_ieh4u1km.dll
Web_Cassini.Day5.WebForm_Add
C:\Users\yangguo\AppData\Local\Temp\Temporary ASP.NET Files\vs\758cfd64\1e0a1365\assembly\dl3\5c75bb14\eb2719c0_a2e8d001\Web_Cassini.dll
打印结果,动态子类和父类所在dll

 3  aspx实现MVC模式的CRUD:

    aspx.cs这个类相当于Controller,获得请求、从Model中拿到数据进行处理,

    aspx.cs中的声明的一些成员变量List<object> list 等相当于Model,只用来临时存储数据,

    aspx这个界面相当于视图View,用于展示数据,

    相互之间都不知道对方是怎么进行的。下面是具体代码:

    public partial class WebForm_Student : System.Web.UI.Page
    {
        protected List<object> list;
        protected void Page_Load(object sender, EventArgs e)
        {
            List<object> list = new MyORM_BLL().SelectAllModel(typeof(TC_STUDENT));
            this.list = list;
        }
    }    public partial class WebForm_Student : System.Web.UI.Page
    {
        protected List<object> list;
        protected void Page_Load(object sender, EventArgs e)
        {
            List<object> list = new MyORM_BLL().SelectAllModel(typeof(TC_STUDENT));
            this.list = list;
        }
    }






<body>
    <form id="form1" runat="server">
    <div>
        <a href="WebForm_StudentEdit.aspx?action=addnew">新增</a>
    <table>
        <thead>
            <tr><th>用户名</th><th>密码</th><th>年龄</th><th>是否富二代</th><th>专业</th><th>性别</th></tr>
        </thead>
        <tbody>
            <%foreach (object student in list) {
                  Console_Core.Model.TC_STUDENT tc = student as Console_Core.Model.TC_STUDENT;
                  %>
                    <tr>
                        <td><%=tc.USERNAME %></td>
                        <td><%=tc.PASSWORD %></td>
                        <td><%=tc.AGE %></td>
                        <td><%var isrich = tc.ISRICH == 1 ? "" : ""; %><%=isrich %></td>
                        <td><%=tc.PROFESSION %></td>
                        <td><%var gender = tc.GENDER == 1 ? "" : ""; %><%=gender %></td>
                        <td><a onclick="return confirm('您确定要编辑吗?')" href="WebForm_StudentEdit.aspx?action=edit&id=<%=tc.ID %>">编辑</a></td>
                        <td><a onclick="return confirm('您确定要删除吗?')" href="WebForm_StudentEdit.aspx?action=delete&id=<%=tc.ID %>">删除</a></td>
                    </tr>    
            <%} %>
            
        </tbody>
    </table>
    </div>
    </form>
</body>
WebForm_StudentList
public partial class WebForm_StudentEdit : System.Web.UI.Page
    {
        MyORM_BLL myORM_BLL = new MyORM_BLL();
        protected TC_STUDENT tc;
        protected string action;
        protected void Page_Load(object sender, EventArgs e)
        {
            string save = Request["save"];
            string action = Request["action"];
            this.action = action;
            if(string.IsNullOrWhiteSpace(save)) //展示
            {
                if(action=="addnew") 
                {
                    this.tc = new TC_STUDENT();
                    this.tc.AGE = 18;
                    this.tc.ID = 0;
                }
                else if(action=="edit")
                {
                    int id=Convert.ToInt32(Request["id"]);
                    TC_STUDENT tc = (TC_STUDENT) myORM_BLL.SelectModelById(typeof(TC_STUDENT), id);
                    this.tc = tc;
                    this.tc.PASSWORD = "";
                }
                else if(action=="delete")
                {
                    int id = Convert.ToInt32(Request["id"]);
                    bool flag = myORM_BLL.DeleteModelById(typeof(TC_STUDENT), id);
                    Response.Redirect("WebForm_Student.aspx");
                }
                else
                {
                    throw new Exception("未知的action:" + action);
                }
            }
            else //保存
            {
                //验证 判空等
                TC_STUDENT tc=new TC_STUDENT();
                tc.USERNAME = Request["USERNAME"];
                tc.PASSWORD = Request["PASSWORD"];
                tc.AGE = Convert.ToInt32(Request["AGE"]);
                tc.PROFESSION = Request["PROFESSION"];
                tc.ISRICH = Request["ISRICH"] == "on" ? 1 : 2;
                switch(Request["GENDER"])
                {
                    case "male": tc.GENDER = 1; break;
                    case "female": tc.GENDER = 2; break;
                    case "both": tc.GENDER = 3; break;
                    default: throw new Exception("未知的Gender:" + Request["GENDER"]);
                }
                if (action == "addnew")
                {
                    bool flag = myORM_BLL.InsertModel(tc, "SE_TC_STUDENT");
                    Response.Redirect("WebForm_Student.aspx");
                }
                else if (action == "edit")
                {
                    int id = Convert.ToInt32( Request["id"]);
                    tc.ID=id;
                    bool flag = myORM_BLL.UpdateModel(tc);
                    Response.Redirect("WebForm_Student.aspx");
                }
                else
                {
                    throw new Exception("未知的action:" + action);
                }
            }
        }
    }






<body>
    <!--  //ID USERNAME PASSWORD AGE ISRICH PROFESSION GENDER -->
    <form action="WebForm_StudentEdit.aspx" method="post">
        <input type="hidden" name="action" value="<%=action %>" /><br />
        <input type="hidden" name="id" value="<%=tc.ID %>" /><br />
        <input type="text" name="USERNAME" value="<%=tc.USERNAME %>" /><br />
        <input type="text" name="PASSWORD" value="<%=tc.PASSWORD %>" /><br />
        <input type="text" name="AGE" value="<%=tc.AGE %>" /><br />
        <input type="checkbox" name="ISRICH" <%=(tc.ISRICH==1?"checked":"") %> />是否富二代<br />
        <input type="text" name="PROFESSION" value="<%=tc.PROFESSION %>" /><br />
        <input type="radio" name="GENDER" id="male" value="male" <%=(tc.GENDER==1?"checked":"") %> /><label for="male">男</label>
        <input type="radio" name="GENDER" id="female" value="female" <%=(tc.GENDER==2?"checked":"") %> /><label for="female">女</label>
        <input type="radio" name="GENDER" id="both" value="both" <%=(tc.GENDER==3?"checked":"") %> /><label for="both">通吃</label><br />
        <input type="submit" name="save" value="保存" /><br />
    </form>
</body>
WebForm_StudentEdit

 4  aspx中runat="server" 的作用:

    一个标签加上runat="server" 后,这个标签中的元素就可以进行操作,可以在aspx.cs即WebFrom_Runat.cs中进行设值和读取。

   原理是:自动生成了一个字段,这个字段被动态子类进行了操作,对字段属性进行了设值和取值。

public partial class WebForm_Runat : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = "WebForm"; //对<head>加上一个 runat='server' 就可以操作<head>中的元素,对它进行设值和取值
            form1.Enctype = "shskdkfhfh"; //d对<form>中的元素进行设值和取值
            txtName.Value = "123456"; //对<input>中元素进行设值和取值
        }
    }







<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="text" name="txtName" id="txtName" runat="server" /><br />
    </div>
    </form>
</body>
WebForm_Runat中的aspx.cs和aspx

 5  WebForm中的控件 Button、LinkButton 和FileUpLoad:

    Button实际就是一个post表单提交;

    LinkButton是一个特殊的超链接,实际是通过JavaScript实现的post表单提交,多与用户进行了一次交互才跳转;

    FileUpLoad文件上载是自动在post表单提交中加上了enctype属性。

<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Button删除" OnClick="Button1_Click" OnClientClick="return confrim(&quot;您确定要删除吗?&quot;);" />
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
        <div>
            <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">LinkButton超链接</asp:LinkButton>
            <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        </div>
        <div>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" style="height: 21px" Text="Button" />
            <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
WebForm_Button_LinkButton_FileUpLoad.aspx
    public partial class WebForm_Button_LinkButton_FileUpLoad : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Button点击实际是post表单提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            Button1.Text = DateTime.Now.ToString();
            Label1.Text = "button的button_click事件实际就是一个post表单提交";
        }

        /// <summary>
        /// LinkButton是一个特殊的超链接,实际是js进行的post表单提交,多了一次与服务器的交互
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            LinkButton1.Text = DateTime.Now.Second.ToString();
            Label2.Text = "LinkButton1_Click超链接点击事件实际也是post表单提交,多了一次与服务器的交互";
            Response.Redirect("http://www.rupeng.com"); //表单提交之后才来跳转
        }

        /// <summary>
        /// FileUpload时点击按钮时也是post表单提交,并自动加了enctype
        /// </summary> 
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
            if (!FileUpload1.HasFile)
            {
                Label3.Text = "文件不能为空";
                return;
            }
            Label3.Text = FileUpload1.PostedFile.ContentLength.ToString();
        }
    }
WebForm_Button_LinkButton_FileUpLoad.aspx.cs

 6  DoPostBack的用法:

    DropDownList下拉列表中SelectedIndexChange事件 去加载下一个下一个列表,

    必须需要同时进行页面数据的提交,即需要AutoPostBack=true 启用,

    DoPostBack的本质就是一个js进行的post表单提交。

    而每次DoPostBack都会进行页面的加载,则会进行累加,所以需要判定只有第一次才加载、或者每次加载前进行Clear。

<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="ddlProvince" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlProvince_SelectedIndexChanged"></asp:DropDownList>
        </div>
        <div>
            <asp:DropDownList ID="ddlCity" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlCity_SelectedIndexChanged"></asp:DropDownList>
        </div>
        <div>
            <asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>
        </div>
    </form>
</body>
WebForm_DoPostBack.aspx
public partial class WebForm_DoPostBack : System.Web.UI.Page
    {
        /// <summary>
        /// 加载省份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack) //不是post提交才加载
            {
            ListItem item1 = new ListItem("江苏", "js");
            ddlProvince.Items.Add(item1);
            ddlProvince.Items.Add(new ListItem("四川", "sc"));
            ddlProvince.Items.Add(new ListItem("广州", "gz"));
            }
        }

        /// <summary>
        /// 加载城市
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCity.Items.Clear();
            string selected = ddlProvince.SelectedValue;
            if(selected=="js")
            {
                ddlCity.Items.Add(new ListItem("苏州", "sz"));
                ddlCity.Items.Add(new ListItem("常州", "cz"));
                ddlCity.Items.Add(new ListItem("南京", "nj"));
            }
            else if (selected == "sc")
            {
                ddlCity.Items.Add(new ListItem("成都", "cd"));
                ddlCity.Items.Add(new ListItem("绵阳", "my"));
                ddlCity.Items.Add(new ListItem("达州", "dz"));
            }
            else
            {
                ddlCity.Items.Add(new ListItem("温州", "wz"));
                ddlCity.Items.Add(new ListItem("潮汕", "cs"));
                ddlCity.Items.Add(new ListItem("佛山", "fs"));
            }
        }

        /// <summary>
        /// 加载乡村
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlCountry.Items.Clear();
            string selected = ddlCity.SelectedValue;
            if(selected=="dz")
            {
                ddlCountry.Items.Add(new ListItem("宣汉", "xh"));
            }
            else if (selected == "sz")
            {
                ddlCountry.Items.Add(new ListItem("昆山", "ks"));
                ddlCountry.Items.Add(new ListItem("张家港", "zjg"));
            }
            else
            { 
            }
        }
    }
WebForm_DoPostBack.aspx.cs

 7  DropDownList/ListBox/RadioButtonList 的DataSource数据绑定:

    dll.DataSource=list 数据绑定需要 dll.DataBind();

    默认绑定所显示的文本DataTextField与值得内容DataValueField是 实例toString()后的内容;

    每次改变实际依然是 js的DoPostBack的表单提交。

<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="ddlStudents" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlStudents_SelectedIndexChanged"></asp:DropDownList>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
        <div>
            <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"></asp:ListBox>
            <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        </div>
        <div>
            <asp:RadioButtonList ID="rbl" DataTextField="USERNAME" DataValueField="ID" runat="server" AutoPostBack="True" OnSelectedIndexChanged="rbl_SelectedIndexChanged"></asp:RadioButtonList>
            <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
WebForm_DataSource.aspx
public partial class WebForm_DataSource : System.Web.UI.Page
    {
        MyORM_BLL myORM_BLL = new MyORM_BLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                List<object> list = myORM_BLL.SelectAllModel(typeof(TC_STUDENT));
                //DropDownList
                ddlStudents.DataSource=list;
                ddlStudents.DataBind(); //默认是把属性的每一项toString()后显示的。 USERNAME(AGE)

                //ListBox
                ListBox1.DataSource = list;
                ListBox1.DataBind();

                //RadioButtonList
                rbl.DataSource = list;
                rbl.DataBind();
            }
        }

        protected void ddlStudents_SelectedIndexChanged(object sender, EventArgs e)
        {
            Label1.Text = ddlStudents.SelectedValue;
        }

        protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Label2.Text = ListBox1.SelectedValue;
        }

        protected void rbl_SelectedIndexChanged(object sender, EventArgs e)
        {
            Label3.Text = rbl.SelectedValue;
        }
    }
WebForm_DataSource.aspx.cs
 public class TC_STUDENT
    {
        //ID USERNAME PASSWORD AGE ISRICH PROFESSION GENDER
        public Int64 ID { get; set; }
        public String USERNAME { get; set; }
        public String PASSWORD { get; set; }
        public Int32 AGE { get; set; }
        public Int32 ISRICH { get; set; }
        public String PROFESSION { get; set; }
        public Int32 GENDER { get; set; }
        public override string ToString()
        {
            return USERNAME + "(" + AGE + ")";
        }
    }
TC_STUDENT

 8  Repeater的用法:

    Repeater是WebForm中最轻量级的控件,可以不用放在<form>中,因为它只用于展示。

    Repeater中的ItemTamplate可以用于拼接<ul>\<select>等各种标签。

    三种<% %> 的区别:

    <%=Test() %> 是调用Test()并打印出结果;

    <%Test() %> 是调用Test() 但是是否打印需要看Test()方法的内部;

    <%#Eval("ID")%> 是进行数据绑定,展示ID属性的值。

<body>
    <form id="form1" runat="server">
        <div>
            <asp:Repeater ID="Repeater1" runat="server">
                <ItemTemplate><%#Eval("USERNAME")%>(<%#Eval("ID")  %>)<br /></ItemTemplate>
            </asp:Repeater>
        </div>
        <div>
            <ul>
            <asp:Repeater ID="Repeater2" runat="server">
                <ItemTemplate>
                    <li><%#Eval("USERNAME") %></li>
                </ItemTemplate>
            </asp:Repeater>
            </ul>
        </div>
        <div>
            <select>
                <asp:Repeater ID="Repeater3" runat="server">
                    <ItemTemplate>
                        <option value="<%#Eval("ID") %>"><%#Eval("USERNAME") %></option>
                    </ItemTemplate>
                </asp:Repeater>
            </select>
        </div>
    </form>
</body>
WebForm_Repeater.aspx
public partial class WebForm_Repeater : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                List<object> list=new MyORM_BLL().SelectAllModel(typeof(TC_STUDENT));
                Repeater1.DataSource = list;
                Repeater1.DataBind();

                Repeater2.DataSource = list;
                Repeater2.DataBind();

                Repeater3.DataSource = list;
                Repeater3.DataBind();
            }
        }
    }
WebForm_Repeater.aspx.cs

 9  ViewState的原理:

    ViewState 相当于一个隐藏字段,在通过代码获取标签中元素的值 是从ViewState中获取该元素的值的;在给html元素赋值时实现是把值赋给了ViewState。

    <system.web>中添加节点 <machineKey compatibilityMode="Framework20SP1"/> 所生成的ViewState 可以通过 ViewStateDecoder2.0 查看。

    ViewState 可以用 this.ViewState["number"] 进行设值和取值。

    ViewState 不能存机密信息。

<body>
    <form id="form1" runat="server">
        <div>
            <%=i %><asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            <input type="hidden" name="i" value="<%=i %>" />
        </div>
        <div>
            <asp:Label ID="Label1" runat="server" Text="0"></asp:Label><asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
        </div>
    </form>
</body>
WebForm_ViewState.asx
public partial class WebForm_ViewState : System.Web.UI.Page
    {
        protected int i;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //1
            //每次点击按钮,请求该类,即httphandler都是new一个新实例,无状态。
            //this.i++;

            //2
            ////如果用Hidden字段 传回httphandler的话 就能实现递增
            //i = Convert.ToInt32(Request["i"]);
            //i++;

            //3
            //viewstate中存了表单提交的i 需要给viewstate设值
            int? number = (int?)this.ViewState["i"];
            if (number == null)
            {
                number = 0;
            }
            number++;
            i = (int)number;
            this.ViewState["i"] = i;
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            int num = Convert.ToInt32(Label1.Text); //通过viewsate获得label的值 ,但是其初始值不会放在viewstate中
            num++;
            Label1.Text = num.ToString(); //把值存入viewstate
        }
    }
WebForm_ViewState.aspx.cs

 10  禁用ViewState的方法:

    禁用ViewState的三种方法:

    (1)在控件级别禁用,只需要设值控件的属性 enableViewState=false;

    (2)在页面级别禁用,只需在页面头部添加     EnableViewState="true";

    (3)在项目级别禁用,只需在<system.web>下面添加节点 <pages enableViewState="false"/>。

    注意:

    (1)只要是 获取界面元素的值,就需要ViewState起到隐藏字段的作用;

    (2)如果是<TextBox>等元素,本身默认通过<from>表单提交,所以可以禁用ViewState;但是<Label>等元素,不会默认表单提交,所以需要启用ViewState;

    (3)当页面只有如<Repeater>等轻量级元素,只表示展示页面,不需要获取页面元素的值时,可以去掉 <form id="form1" runat="server">的runat,就可以去掉第一个ViewState.。

<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater ID="Repeater1" runat="server" EnableViewState="False">
            <ItemTemplate><%#Eval("USERNAME") %> <br /></ItemTemplate>
        </asp:Repeater>
    </div>
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
        <div>
            <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
            <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        </div>
        <div>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
            <asp:Label ID="Label3" runat="server" Text="1"></asp:Label>
        </div>
    </form>
</body>
WebForm_EnabledViewState.aspx
 public partial class WebForm_EnabledViewState : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<object> list = new MyORM_BLL().SelectAllModel(typeof(TC_STUDENT));
            Repeater1.DataSource = list;
            Repeater1.DataBind();
        }

        //如果TextBox1的值>100就变红 禁用ViewState
        protected void Button1_Click(object sender, EventArgs e)
        {
            //只要需要获取元素的值,就需要ViewState这个隐藏字段,但是text本来就是通过form提交的 所以不需要ViewState
            int num=Convert.ToInt32(TextBox1.Text); 
            if (num>100)
            {
                Label1.ForeColor = Color.Red;
                Label1.Text = "不能超过100";
            }
        }

        //如果Label2为红色就变蓝,否则变红 启用ViewState
        protected void Button2_Click(object sender, EventArgs e)
        {
            //需要获取元素的值,所以需要ViewState这个隐藏字段,label不会默认form提交,所以需要启用ViewState
            if (Label2.ForeColor == Color.Red)
            {
                Label2.ForeColor = Color.Blue;
            }
            else
            {
                Label2.ForeColor = Color.Red;
            }
        }

        //TextBox自增 和Label自增
        protected void Button3_Click(object sender, EventArgs e)
        {
            //TextBox2的值默认是form提交的 不需要ViewState 所以可以禁用它
            int num = Convert.ToInt32(TextBox2.Text); 
            num++;
            TextBox2.Text = num.ToString();

            //Label3的值默认是不会被form提交的,所以获取它的值,需要启用ViewState 
            int lab = Convert.ToInt32(Label3.Text); 
            lab++;
            Label3.Text = lab.ToString();
        }
    }
WebForm_EnabledViewState.aspx.cs

 11  轻量级的CRUD:

    注意:

    (1)展示时必须是 if(!IsPostBack) ,因为<button>提交时实际是js的DoPostBack表单提交。

    (2)新增或编辑时要消除所有ViewState,需要在页面顶部加上 EnableEventValidation="false"。

    (3)禁用ViewState后,DropDownList只能从Request["ddlBoss"]中取值,不能从ddlBoss.SelectedValue,因为后者本质是从ViewState中取值的。

    (4)WebForm自动把action和id放到了<from>中,并以QueryString进行传递,所以不需要另外增加Hidden标签。

    例子 --公司(老板)CRUD如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm_CompanyList.aspx.cs" Inherits="Web_Cassini.Day5.WebForm_CompanyList" 
   EnableViewState="false"%>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <a href="WebForm_CompanyEdit.aspx?action=addnew">新增</a>
        <table>
            <thead>
                <tr><th>公司名称</th><th>老板</th><th></th><th></th></tr>
            </thead>
            <tbody>
                 <asp:Repeater ID="Repeater1" runat="server">
                     <ItemTemplate>
                         <tr>
                             <td><%#Eval("NAME") %></td>
                             <td><%#Eval("BOSSNAME") %></td>
                             <td><a href="WebForm_CompanyEdit.aspx?action=edit&id=<%#Eval("ID") %>">编辑</a></td>
                             <td><a onclick="return confrim('您确定要删除吗?');" href="WebForm_CompanyEdit.aspx?action=delete&id=<%#Eval("ID") %>">删除</a></td>
                         </tr>
                     </ItemTemplate>
                 </asp:Repeater>
            </tbody>
        </table>
       
    </div>
    </form>
</body>
</html>
WebForm_CompanyList.aspx
using Console_Core.BLL;
using Console_Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web_Cassini.Day5
{
    public partial class WebForm_CompanyList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<TC_COMPANY_ORI> list = new CompanyBLL().GetAllCompany();
            Repeater1.DataSource = list;
            Repeater1.DataBind();
        }
    }
}
WebForm_CompanyList.aspx.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm_CompanyEdit.aspx.cs" Inherits="Web_Cassini.Day5.WebForm_CompanyEdit" 
   EnableViewState="false"
    EnableEventValidation="false" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <!--本来应该有个hidden的action和id的,但是aspx默认会把他们以QueryString进行传递-->
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
            <asp:DropDownList ID="ddlBoss" DataTextField="NAME" DataValueField="ID" runat="server"></asp:DropDownList><br />
            <asp:Button ID="btnSave" runat="server" Text="保存" OnClick="btnSave_Click" /><br />
        </div>
    </form>
</body>
</html>
WebForm_CompanyEdit.aspx
using Console_Core.BLL;
using Console_Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web_Cassini.Day5
{
    public partial class WebForm_CompanyEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack) //展示
            {
                string action = Request["action"];
                //获得所有老板信息
                List<object> listBosses = new MyORM_BLL().SelectAllModel(typeof(TC_BOSS));
                ddlBoss.DataSource = listBosses;
                ddlBoss.DataBind();
                if(action=="addnew")
                {
                    txtName.Text = "有限责任公司";
                }
                else if (action=="edit")
                {
                    //验证 id格式 ?
                    int id = Convert.ToInt32(Request["id"]);
                    TC_COMPANY com = (TC_COMPANY)new MyORM_BLL().SelectModelById(typeof(TC_COMPANY), id);
                    txtName.Text = com.NAME;
                    ddlBoss.SelectedValue = com.BOSSID.ToString();
                }
                else if(action=="delete")
                {
                    //验证 id?
                    int id =Convert.ToInt32( Request["id"]);
                    bool flag = new MyORM_BLL().DeleteModelById(typeof(TC_COMPANY), id);
                    Response.Redirect("WebForm_CompanyList.aspx");
                }
                else
                {
                    throw new Exception("action错误:" + action);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            //由于aspx默认把action和id以QueryString传递,所以不需要hidden字段
            string action = Request["action"];
            //获得共同的属性值
            TC_COMPANY com=new TC_COMPANY();
            //验证 非空及格式?
            com.NAME = Request["txtName"];
            //ddlBoss.SelectedValue 是以ViewState进行获取的  ---------
            com.BOSSID = Convert.ToInt32(Request["ddlBoss"]);
            if (action == "addnew")
            {
                bool flag = new MyORM_BLL().InsertModel(com, "SE_TC_STUDENT");
                Response.Redirect("WebForm_CompanyList.aspx");
            }
            else if (action == "edit")
            {
                //验证 ID ?
                com.ID = Convert.ToInt32(Request["id"]);
                bool flag = new MyORM_BLL().UpdateModel(com);
                Response.Redirect("WebForm_CompanyList.aspx");
            }
            else
            {
                throw new Exception("action错误:" + action);
            }
        }
    }
}
WebForm_CompanyEdit.aspx.cs

 

 

 

 

 

 

  

 

posted on 2015-09-06 20:19  AdolphYang  阅读(1041)  评论(0编辑  收藏  举报