ASP IsPostBack,服务器端控件,__VIEWSTATE

89 篇文章 0 订阅
本文深入探讨ASP.NET中IsPostBack属性的作用,介绍服务器控件的工作原理,并详细解析用于状态管理的__VIEWSTATE机制,帮助开发者理解页面生命周期及其在Web应用程序开发中的重要性。
摘要由CSDN通过智能技术生成

xxx.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 类库名.WebApp
{
    public partial class AddUserInfo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //服务器端控件(runat="server"),都会在客户端的html页面中有一个__VIEWSTATE隐藏域(该隐藏域的value用于保存html的数据,影响网页加载)
            //如果要托服务器端的控件,则必须要有一个服务器端的<form runat="server" >标签 (该标签一般会自动就有)。
            //IsPostBack:如果是POST请求该属性的值为true,如果是GET请求该属性的值为false.
            //IsPostBack:是根据__VIEWSTATE隐藏域进行判断的,如果是POST请求那么该隐藏域的值会提交到服务端,那么IsPostBack属性也就为true.如果将form标签的runat="server"去掉,那么就不能用该属性进行判断是POST请求还是GET请求。因为去掉form标签的runat="server",那么就不会再产生 __VIEWSTATE隐藏域了。
            if(IsPostBack)  //如果是post请求
            {
                InsertUserInfo();
            }
            
            //如果没有用服务器端控件(手写form标签的method,action 属性),则需要添加一个isPostBack的隐藏域,来判断是post还是get请求。
            //如果隐藏域的值不为空,表示用户单击了提交按钮发出了POST请求
            //if (!string.IsNullOrEmpty(Request.Form["isPostBack"]))
        }
        protected void InsertUserInfo()
        {
            Model.UserInfo UserInfo = new Model.UserInfo();
            UserInfo.UserName=Request.Form["txtName"];
            UserInfo.UserPass = Request.Form["txtPwd"];
            UserInfo.Email = Request.Form["txtMail"];
            UserInfo.RegTime = DateTime.Now;
            BLL.UserInfoService UserInfoService = new BLL.UserInfoService();
            if (UserInfoService.AddUserInfo(UserInfo))
            {
                Response.Redirect("UserInfoList.aspx");
            }
            else
            {
                Response.Redirect("/Error.html");
            }
        }
    }
}
xxx.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddUserInfo.aspx.cs" Inherits="类库名.WebApp.AddUserInfo" %>

<!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">  <%--服务器端的form标签--%>
    <div>
     用户名:<input type="text" name="txtName" /><br />
        密码:<input type="password" name="txtPwd" /><br />
        邮箱:<input type="text" name="txtMail" /><br />
    <%--  <input type="hidden" name="isPostBack" value="aaa" />  --%>  <%--如果不用服务器端的控件(没有__VIEWSTATE隐藏域),就需要手写isPostBack隐藏域,用于判断是post还是get请求--%>
        <input type="submit" value="添加用户" />

    </div>
    </form>
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值