ASP.NET基础

来源:互联网 发布:2016志鸿优化设计答案 编辑:程序博客网 时间:2024/06/14 21:57

ASP.NET基础

1.如何理解viewstate?
参考What is viewstate in asp.net - Part 3

Web应用是基于HTTP,HTTP协议是无状态协议,它并不保存请求的状态,所以可以使用viewstate 来保存不同请求间的状态。

ClicksCount = (int)ViewState["Clicks"] + 1;

ViewState数据序列化为base64编码的字符串,保存在隐藏域__ViewState

ASP.NET的服务器控件会保存状态,而HTML控件则不会。HTML控件可以通过添加runat="server"变为ASP.NET服务器控件

2.web应用生命周期中的事件
参考Events in the life cycle of a web application - Part 4

如果想要在多个Web表单中提供数据,在ASP.NET中有如下的方式:
1. Query Strings
2. Cookies
3. Session State
4. Application State

注意Session State 与Application State、ViewState的区别,可参考Difference between ViewState, Session State and Application State in asp.net - Part 5

页面的生命周期ASP.NET Page Life Cycle Events - Part 6

当一个webform的请求到来时,事件执行的顺序如下:
1. Web Application creates an instance of the requested webform.
2. Processes the events of the webform.
3. Generates the HTML, and sends the HTML back to the requested client.
4. The webform gets destroyed and removed from the memory.

3.服务器控件的事件
参考ASP.NET Server control events - Part 7

控件的事件类型可分为3类:

1.Postback事件-提交webpage,直接到服务器处理。如button的click事件就是Postback事件
2.Cached事件-这些事件保存在page的viewstate中待处理,直到一个postback事件发生。例如,TextBoxTextChanged事件,DropDownListSelectedIndexChanged 事件。Cached事件可被转化为Postback事件,通过设置AutoPostBacktrue
3.Validation事件-在page被post back到server之前,在客户端发生

4.对IsPostBack的理解
参考IsPostBack in asp.net - Part 8

IsPostBack is a Page level property, that can be used to determine whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.

5.Page的生命周期

参考ASP.NET Page Life Cycle Events - Part 6

  • Page_PreInit在页面初始化事件之前发生。在此阶段,设置IsPostBackIsCallbackIsCrossPagePostBack 属性。这个事件中可以动态的设置master page和web应用的主题。PreInit在使用动态控件时被广泛使用。
  • Page_Init使用此事件来读取或初始化控件属性。
  • Page_InitComplete
  • Page_PreLoad
  • Page_Load
  • Page_LoadComplete
  • Page_PreRender
  • Page_PreRenderComplete
  • Page_Unload

ASP.NET控件

1.TextBox控件
参考ASP.NET TextBox Control - Part 10

属性:

  • AutoPostBack- By default, the TextChanged event of a TextBox control is cached in the viewstate, and is executed when the webform is submitted thru a postback by clicking the button control. If you want to change this behaviour, and post the webform immediately when the Text is changed, set AutoPostBack to true. Setting this property to true, will convert the cached event into a postback event.

方法

  • Focus()

事件:

  • TextChanged

2.RadioButton控件
属性

  • Checked表示是否选中
  • GroupName默认的,每个Radio不是互斥的。如果想要互斥,对Radio要使用相同的GroupName

事件

  • CheckedChanged-当radio button的check状态方法改变时触发。注意默认事件是缓存在viewstate中的,与TextBox类似

3.CheckBox控件
CheckBox控件与RadioButton控件类似,但它有个Focus()方法

4.HyperLink控件

属性:

  • ImageUrl图片的url,如果同时指定Text和ImageUrl,显示image。如果image不可用呢,则显示Text
  • NavigateUrl导航页面的地址
  • Target与HTML的<a>标签的target类似

5.Button、LinkButton、ImageButton
LinkButton与HyperLink类似

所有的3个按钮都有client端点击事件和server端点击事件

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/like.png"             onclick="ImageButton1_Click"  OnClientClick="return confirm('Are you sure want to delete?')"/>

除了在设计时添加client端的点击事件,也可以在运行时添加

    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            Button1.Attributes.Add("onclick", "return confirm('Be careful')");        }    }

如何在LinkButton中传递参数?
使用CommandArgument 属性,如下:

<asp:LinkButton ID="lbtnDel" runat="server" OnClientClick="return confirm('确定删除?')" OnClick="btnDel_Click" CommandArgument='<%#Eval("DishId") %>'>删除</asp:LinkButton>

onClick方法中获取传递的参数:

        protected void btnDel_Click(object sender, EventArgs e)        {            string dishId = ((LinkButton)sender).CommandArgument;         }

6.DropDownList控件
在设计时添加item:

        <asp:DropDownList ID="DropDownList1" runat="server">            <asp:ListItem Value="1">Male</asp:ListItem>            <asp:ListItem Value="2" Selected="True">Female</asp:ListItem>        </asp:DropDownList>

指定某个listItem被选中,设置SelectedTure
隐藏某个listItem,设置Enabledfalse

也可以在运行时添加listItem:

    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            ListItem maleListItem = new ListItem("Male", "1");            ListItem femaleListItem = new ListItem("Female", "2");            DropDownList1.Items.Add(maleListItem);            DropDownList1.Items.Add(femaleListItem);        }    }

DropDownListListItem对象的集合,如下的控件与DropDownList类似:

  1. CheckBoxList
  2. RadioButtonList
  3. BulletedList
  4. ListBox

DropDownList绑定数据库中的数据:
参考Data bind asp.net dropdownlist with data from the database - Part 17

如下,从数据库中取出数据,绑定到DropDownList上:

    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;            using (SqlConnection connection = new SqlConnection(CS))            {                SqlCommand cmd = new SqlCommand("select * from tblCity", connection);                connection.Open();                SqlDataReader rdr = cmd.ExecuteReader();                DropDownList1.DataTextField = "CityName";                DropDownList1.DataValueField = "CityId";                DropDownList1.DataSource = rdr;                DropDownList1.DataBind();            }        }    }

注意要指定DropDownListDataTextFieldDataValueField ,否则的话显示的数据就System.Data.Common.DataRecordInternal

7.Literal控件
参考Literal control in asp.net - Part 41
LiteralLabel控件很类似,都是用来在webform上显示文字。
Label控件渲染时,将文字包裹在span标签中,如下:

<asp:Label ID="Label1" runat="server"  Text="Lable Text" ForeColor="Red" Font-Bold="true" ></asp:Label>

被渲染为:

<span id="Label1" style="color:Red;font-weight:bold;">Lable Text</span>

而literal控件,并不会被标签包裹,如下:

<asp:Literal ID="Literal1" runat="server" Text="Literal Control Text"></asp:Literal>

将被渲染为:

Literal Control Text

默认情况下,LabelLiteral控件不会encode它们所显示的text,所以如下的HTML将会显示一个javascriptalert

<asp:Label ID="Label" runat="server" Text="<script>alert('Lable Text');</script>"> </asp:Label><br /><asp:Literal ID="Literal1" runat="server" Text="<script>alert('Literal Text');</script>"></asp:Literal>

要编码LabelText,使用Server.HtmlEncode()方法

母版页

母版页和内容页的生命周期
参考Part 152 - Master page content page user control life cycle in asp.net

User control initMaster initContent InitContent loadMaster loadUserControl Load 

文件上传

Server.MapPath(".")返回你正在运行的页面的当前物理目录
Server.MapPath("..")返回正在运行的页面的父目录
Server.MapPath("~")返回应用程序的根目录的物理路径

参考Fileupload control in asp.net - Part 30

文件上传使用asp:FileUpload控件

FileUpload1.HasFile是否选择了一个文件
FileUpload1.FileName选择文件的文件名
获取文件的扩展名,并判断:

    string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);    if (fileExtension.ToLower() != ".doc" && fileExtension.ToUpper() != ".docx")

获取文件大小,以字节为单位

int fileSize = FileUpload1.PostedFile.ContentLength;

上传文件:

FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileUpload1.FileName));

Calendar

参考:

  • Asp.net calendar control - Part 32
  • Asp.net calendar control properties and events - Part 33

一些日期处理的形式:

Response.Write("ToString() - " + DateTime.Now.ToString() + "<br/>");Response.Write("ToLongDateString() - " + DateTime.Now.ToLongDateString() + "<br/>");Response.Write("ToShortDateString() - " + DateTime.Now.ToShortDateString() + "<br/>");Response.Write("ToLongTimeString() - " + DateTime.Now.ToLongTimeString() + "<br/>");Response.Write("ToShortTimeString() - " + DateTime.Now.ToShortTimeString() + "<br/>");

输出为:

ToString() - 2017/8/27 10:07:13ToLongDateString() - 2017年8月27日ToShortDateString() - 2017/8/27ToLongTimeString() - 10:07:13ToShortTimeString() - 10:07

DateTime字符串格式化

Response.Write("d - " + DateTime.Now.ToString("d") + "<br/>");Response.Write("D - " + DateTime.Now.ToString("D") + "<br/>");Response.Write("dd/MM/yyyy - " + DateTime.Now.ToString("dd/MM/yyyy") + "<br/>");Response.Write("dd/MMMM/yyyy - " + DateTime.Now.ToString("dd/MMMM/yyyy") + "<br/>");Response.Write("dd/MMMM/yy - " + DateTime.Now.ToString("dd/MMMM/yy") + "<br/>");Response.Write("MM/dd/yy - " + DateTime.Now.ToString("MM/dd/yy") + "<br/>");

输出为:

d - 2017/8/27D - 2017年8月27日dd/MM/yyyy - 27/08/2017dd/MMMM/yyyy - 27/八月/2017dd/MMMM/yy - 27/八月/17MM/dd/yy - 08/27/17

HiddenField

1.HiddenFieldValue属性用来设置或者获取value
2.value被存储为一个字符串
3.ViewState使用HiddenFiled来保持状态跨回发
4.HiddenField被渲染为<input type= "hidden"/>元素

可使用View state、QueryStrings、session state和cookies 来代替HiddenField

使用HiddenField的优势:
可使用JavaScript获取数据:

<script type="text/javascript">    function GetHiddenFieldValue()     {        alert(document.getElementById('HiddenField1').value);    }</script>

panel

参考:

  • Asp.net panel control - Part 42

panel控件可以用作其它控件的一个容器。

原创粉丝点击