none
ASP.NET Web 表单常见问题 RRS feed

全部回复

  •   

    1.JavaScript

     

    1.1 如何获得客户端日期和时间?  [回到顶端]

      

    你可以使用java script函数显示日期和时间:

     

    <script type="text/javascript">

        function displayTime()

        {

            var localTime = new Date();

            var year= localTime.getYear();

            var month= localTime.getMonth() +1;

            var date = localTime.getDate();

            var hours = localTime .getHours();

            var minutes = localTime .getMinutes();

            var seconds = localTime .getSeconds();   

            var div=document.getElementById("div1");

            div.innerText=year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;

        }

    </script>

     

    接着你可以在web 页面中调用它.

     

     <body onload="displayTime();">

        <form id="form2" runat="server">

        <div id="div1"></div>

        </form>

    </body>

      

    相关帖子:

    http://forums.asp.net/p/1247758/2303034.aspx

     

     

    1.2 如何通过使用JavaScript访问控件?  [回到顶端]

     

    JavaScript中引用控件的ClientID(UniqueID)属性.

     

    protected void Page_Load(object sender, EventArgs e)

    {

        Button btn= new Button();

        btn.ID = "btn5";

        btn.Attributes.Add("runat", "server");

        btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");

        btn.Text = "Test";

        this.form1.Controls.Add(btn);

    }

     

    function pop(InputBoxID)

    {

        var InputControl = document.getElementById(InputBoxID);

        alert(InputControl.value);

    }

      

    或者你可以使用下面的方法:

     

    btn.Attributes.Add("onclick", "pop(this)");

    function pop(InputBox)

    {

        alert(InputBox.value);

    }

      

    相关帖子:

    http://forums.asp.net/p/1239593/2260331.aspx#2260331

     

     

    1.3 如何通过JavaScript调用服务器端函数?  [回到顶端]

     

    首先, 你拖放一个button控件,并把服务器端函数放到button Click事件中 

     

    protected void Button1_Click(object sender, EventArgs e)

    {

       FunctionName();

    }

      

    其次,你可以通过下面的JavaScript 调用服务器端函数,

    document.getElementById("Button1").click();

      

    相关帖子:

    http://forums.asp.net/p/1242420/2274228.aspx

     

     

    1.4 如何使用JavaScript 代码获得服务器端变量?  [回到顶端]

     

    <asp:HiddenField ID="HiddenField1" runat="server" />   

    public partial class LoginDemo : System.Web.UI.Page

    {  

        private string str="hello";

        protected void Page_Load(object sender, EventArgs e)

        {

            HiddenField1.Value=str;

        }

    }

      

    接着使用javascipt你可以访问控件HiddenField1:

     

    <script type="text/JavaScript">

    Var tt=document.getElementByID(“HiddenField1”);

    alert(tt.value);

    </script>

      

    相关帖子:

    http://forums.asp.net/p/1000655/1319119.aspx

     

     

    1.5 如何在ASP.NET中使用JavaScript 去分配值到隐藏变量?  [回到顶端]

     

    我们可以使用JavaScript去设置隐藏控件的值并且在回传后在服务器端得到它的值。

     

    <input id="Hidden1" type="hidden" />

    <script type="text/JavaScript">

    var str=”hello”

    document.getElementByID(“Hidden1”).value=str

    </script>

    protected void Page_Load(object sender, EventArgs e)

    {

        string str=request["Hidden1"].ToString();

    }

      

    相关帖子:

    http://forums.asp.net/p/1262153/2362090.aspx

     

      

    1.6 如何在后台代码注册JavaScript函数  [回到顶端]

      

    使用ResterStartupScript

    this.Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","<script>alert(‘hello’);</script>");

      

    使用 Literal 控件,

    private void Button2_Click(object sender, System.EventArgs e)

    {

        string str;

        str="<script language='JavaScript'>";  

        str+="selectRange()";

                       str+="<script>";

        Literal1.Text=str;

    }

      

    相关帖子:

    http://forums.asp.net/p/981603/1257057.aspx#1257057 

     

     

    1.7 如何延迟5秒显示图像  [回到顶端]

      

    使用如下脚本,你可以看见实时可点击的轮流图像而不需要横幅轮换软件或页面的重新装载/刷新。每5秒你应当看到一个新的轮换横幅:

     

    <%@ Page Language="C#" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head id="Head1" runat="server">

        <title>JavaScript</title>

        <script language="javascript" type="text/javascript">

        var image="";

        var banners=0;

        function loadbanners() {

       if (banners==1)

          {

             image="images/AJAX.gif";

          }

       if (banners==2)

          {

             image="images/ASPDotNet.gif";

          }

       if (banners==3)

          {

             image=" images/MSDN.gif";

          }

          }

          function cycle()

          {

            if (++banners > 3)

            banners=1;

            loadbanners();

            document.getElementById("banner1").src =image;

            window.setTimeout('cycle();',5000);

          }

        </script>

    </head>

    <body onload="cycle();">

        <form id="form2" runat="server">

        <div>

            <img alt="" id="banner1" src="images/start.png" />

        </div>

        </form>

    </body>

    </html>

      

    相关帖子:

    http://forums.asp.net/p/1213103/2147140.aspx

     

     

    1.8 如何得到浏览器屏幕设置并应用于页面控件  [回到顶端]

      

    你可以使用JavaScript, 假设控件类型是<image>, 参看下面代码:

     

    <html>

    <body>

    <input onclick="resizeImage()"/>

    <img src="http://www.microsoft.com/library/toolbar/3.0/images/banners/ms_masthead_ltr.gif"  id="Img1"  />

    <script language="JavaScript">

        var winWidth = 0;

        var winHeight = 0;

        function resizeImage(){

        var img=document.getElementById("testImage")

        if (window.innerWidth)

               winWidth = window.innerWidth;

         else if ((document.body) && (document.body.clientWidth))

               winWidth = document.body.clientWidth;

         if (window.innerHeight)

               winHeight = window.innerHeight;

         else if ((document.body) && (document.body.clientHeight))

               winHeight = document.body.clientHeight; 

         if (document.documentElement  && document.documentElement.clientHeight &&

                                              document.documentElement.clientWidth)

         {

             winHeight = document.documentElement.clientHeight;

             winWidth = document.documentElement.clientWidth;

         }

         img.width= winHeight;

         img.width= winWidth;

        }

    </script>

    </body>

    </html>

     

    请删除控件的样式如果呈现的话。

     

    相关帖子:

    http://forums.asp.net/p/1228180/2212987.aspx

     

     

    1.9 如何在用户关闭窗体时清除session  [回到顶端]

      

    使用代码,

    <script type="text/javascript">
    function window.onbeforeunload()
    {
        var xmlHttp;
        try
        {
            // Firefox, Opera 8.0+, Safari
            xmlHttp=new XMLHttpRequest();
        }
        catch (e)
        {
            // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
        if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
        {
            xmlhttp.open("GET","exit.aspx",false);
            xmlhttp.send();
        }
     }
    </script>

      

    相关帖子:

    http://forums.asp.net/p/1237752/2255401.aspx

     


    If you have any feedback on this FAQ please send it to fbmsdn@microsoft.com
    2009年7月21日 7:34
  •  

    2. 页面之间传递数据的不同方式  [回到顶端]

     

    2.1 如何使用cookies  [回到顶端]

     

    创建一个名为page1.aspx的页面, 接着拖放一个buttonTextBoxpage上。双击 button并添加下面的代码:

     

    protected void Button1_Click(object sender, EventArgs e)

    {

        HttpCookie cookie = new HttpCookie("UserName");

        cookie.Value = TextBox1.Text;

        cookie.Expires = DateTime.Now.AddDays(1);

        Response.Cookies.Add(cookie);

        Response.Redirect("Page2.aspx");

    }

      

    page1.aspx, 

    <div>

         <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    </div>

      

    对于 page2.aspx, 双击form并把下面的代码放在里面:

    protected void Page_Load(object sender, EventArgs e)

    {

        if (Request.Cookies["UserName"] != null)

            Response.Write(Request.Cookies["UserName"].Value);

    }

      

    相关帖子:

    http://forums.asp.net/t/1223291.aspx

    Asp.Net Cookies Overview

    How to: Read a Cookie

    How to: Delete a Cookie

    ASP.NET State Management Overview

    ASP.NET State Management Recommendations

     

     

    2.2 如何使用QueryString  [回到顶端]

     

    private void Button1_Click (object sender, System.EventArgs e)

    {

        string url;

                        url="anotherwebform.aspx?name=" +

                        TextBox1.Text + "&email=" + TextBox2.Text;

                        Response.Redirect(url);

    }

      

    目标web窗体

    private void Page_Load (object sender, System.EventArgs e)

    {

        Label1.Text=Request.QueryString["name"];

        Label2.Text=Request.QueryString["email"];

    }

      

    相关帖子:

    http://forums.asp.net/p/1223291/2191155.aspx

    ASP.NET State Management Overview

    ASP.NET State Management Recommendations

     

     

    2.3 如何使用Session  [回到顶端]

      

    private void Button1_Click(object sender, System.EventArgs e)

    {

        //Drag TextBox1 and TextBox2 onto a web form

        Session["name"]=TextBox1.Text;

        Session["email"]=TextBox2.Text;

        Server.Transfer("anotherwebform.aspx");

    }

      

    目标web 窗体

    private void Page_Load(object sender, System.EventArgs e)

    {

        Label1.Text=Session["name"].ToString();

        Label2.Text=Session["email"].ToString();

        Session.Remove("name");

        Session.Remove("email");

    }

      

    相关帖子:

    http://forums.asp.net/p/1255625/2333723.aspx

    How to: Read Values from Session State

    How to: Save Values in Session State

    HttpSessionState Class

    ASP.NET State Management Overview

    ASP.NET State Management Recommendations

     

     

    2.4 如何使用HttpContext  [回到顶端]

      

    //Page1.aspx 在传递之前在上下文存储值

    Context.Items("UserName") = txtName.Text;

    Server.Transfer("Page2.aspx");

     

    //Page2.aspx Page1context 获取值

    string sName;

    sName = Context.Items("UserName").ToString;

    Response.Write("Your name is " + sName);

      

    相关帖子:

    http://forums.asp.net/t/1238286.aspx

    HttpContext Class

    ASP.NET State Management Overview

    ASP.NET State Management Recommendations

     

      

    2.5 如何使用PreviousPage  [回到顶端]

     

    FirstForm.aspx

    <asp:Button id="buttonPassValue" runat="server" Text="Button" PostBackUrl="~/SecondForm.aspx">

    </asp:Button>

     

    SecondForm.aspx.cs

    TextBox1.Text = Request.Form["TextBox1"].ToString();

    或者

    SecondForm.aspx.cs

    TextBox textBoxTemp = (TextBox) PreviousPage.FindControl("TextBox1");

    TextBox1.Text = textBoxTemp.Text;

     

    正如你所注意的,这是一个在页面间传递值的简单巧妙的方式

     

    相关帖子:

    http://forums.asp.net/p/1048041/1474374.aspx

    Page.PreviousPage Property

    How to: Pass Values Between ASP.NET Web Pages

     

     

    2.6 如何使用Submit控件?  [回到顶端]

      

    page1.aspx,   

    <%@ Page Language="C#" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <script language="javascript">

        function CopyTextToHiddenField()

        {

            var textbox1Value = document.getElementById("<%=TextBox1.ClientID%>").value;

            document.forms[1].document.getElementById("Hidden1").value = textbox1Value;

        }

    </script>

    </head>

    <body>

        <form id="form1" runat="server">

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        </form>

        <form name="SubmittedForm" action="page2.aspx" method="post">

        <input id="Submit1" type="submit" value="submit" onclick="CopyTextToHiddenField()" />

        <input name="Hidden1" type="hidden" />

        </form>

    </body>

    </html>

     

    page2.aspx,

    <%@ Page Language="C#" %>

     

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

     

    <script runat="server">

     

        protected void Page_Load(object sender, EventArgs e)

        {

            Response.Write(Request.Form["Hidden1"]);

        }

    </script>

     

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head id="Head1" runat="server">

    </head>

    <body>

        <form id="form1" runat="server">

        <div>

        </div>

        </form>

    </body>

    </html>

     

    相关帖子:

    http://forums.asp.net/p/1257184/2339923.aspx

     

     

    2.7 如何使用 Server.Transfer  [回到顶端]

      

    page1.aspx,

    <%@ Page Language="C#" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        protected void Button_Click(object sender, EventArgs e)

        {

            Server.Transfer("page2.aspx", true);

     

        }

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head id="Head1" runat="server">

    </head>

    <body>

        <form id="form1" runat="server">

        <div>

            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button_Click" />

            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        </div>

        </form>

    </body>

    </html>

     

    page2.aspx,

    <%@ Page Language="C#" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        protected void Page_Load(object sender, EventArgs e)

        {

            Response.Write(Request.Form["TextBox1"]);

        }

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head id="Head1" runat="server">

    </head>

    <body>

        <form id="form1" runat="server">

        <div>

           

        </div>

        </form>

    </body>

    </html>

     

    相关帖子:

    http://forums.asp.net/p/1262144/2362078.aspx

    http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

    http://dotnetslackers.com/community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx

    Cross-Page Posting in ASP.NET Web Pages

    How to: Determine How ASP.NET Web Pages Were Invoked

     


    If you have any feedback on this FAQ please send it to fbmsdn@microsoft.com
    2009年7月21日 7:35
  •  

    3.文件上传  [回到顶端]

     

    3.1 如何上传一个文件?  [回到顶端]

     

    if (FileUpLoad1.HasFile)

       FileUpLoad1.SaveAs(Server.MapPath("upload")+ "\\" + FileUpLoad1.FileName);

    }

     

    相关帖子:

    FileUpload Web Server Control OverviewFileUpload Class

     

     

    3.2 如何一次上传多个文件?  [回到顶端]

     

    请查阅下面的文章,在这篇文章中,Haissam Abdul Malak 将解释如何使用HtmlInputFile 控件有条理的上传多个文件。

     

    相关帖子:

    http://forums.asp.net/t/1263738.aspx

    http://aspalliance.com/1221_CodeSnip_Uploading_Multiple_Files_At_Once.all

     

     

    3.3 当使用ASP.NET FileUpload控件上传大文件时为何失败?  [回到顶端]

      

    由于安全原因, ASP.NET就上传的文件大小来说是受限制的.默认的最大文件大小是4 MB, 但是这个可以通过Machine.config<httpRuntime>元素的MaxRequestLength属性来修改。

     

    <httpRuntime executionTimeout="240" maxRequestLength="20480" />

     

    相关帖子:

    http://forums.asp.net/t/1074332.aspx

    http://forums.asp.net/p/1106754/1696069.aspx#1696069

     

     

    3.4 如何只上传图像文件?  [回到顶端]

      

    参见代码,

     

    Fileupload.aspx:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Fileupload.aspx.cs" Inherits="FileuploadDemo" %>

    <!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>Upload Image Demo</title>

    </head>

    <body>

        <form id="form1" runat="server">

        <div>

            <asp:Image ID="Image1" runat="server" />

            <asp:FileUpload ID="FileUpload1" runat="server" />

            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />

        </div>

        </form>

    </body>

    </html>

     

    Fileupload.aspx.cs:

    using System;

    using System.Collections;

    using System.Configuration;

    using System.Data;

    using System.Linq;

    using System.Web;

    using System.Web.Security;

    using System.Web.UI;

    using System.Web.UI.HtmlControls;

    using System.Web.UI.WebControls;

    using System.Web.UI.WebControls.WebParts;

    using System.Xml.Linq;

     

    public partial class FileuploadDemo : System.Web.UI.Page

    {

        protected void btnSubmit_Click(object sender, EventArgs e)

        {

            string fileFullname = this.FileUpload1.PostedFile.FileName;

            string dataName = DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss");

            string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\\") + 1);

            string type = fileFullname.Substring(fileFullname.LastIndexOf(".") + 1);

            if (FileUpload1.PostedFile.ContentType.ToUpper().IndexOf("IMAGE") > -1)

            {

                System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);

                int Width = img.Width;

                int Height = img.Height;

     

                if (Width > 1000 || Height > 1000 || FileUpload1.PostedFile.ContentLength > 1024 * 1024 * 200)

                {

                    this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",

                          "<script language='javascript'>alert('The image size is too large!');</script>");

                }

                else

                {

                    if (type == "jpg" || type == "gif" || type == "bmp" || type == "JPG" || type == "GIF")

                    {

                        string ImagePath = "images/";

                        string sPath = Server.MapPath(ImagePath) + dataName + fileName;

                        string imgPath = ImagePath + dataName + fileName;

                        this.FileUpload1.PostedFile.SaveAs(sPath);

                        this.ClientScript.RegisterStartupScript(this.GetType(),

                              "Startup", "<script language='javascript'>alert('Success!');</script>");

                        this.Image1.ImageUrl = imgPath;

                        this.btnSubmit.Enabled = false;

                        this.btnSubmit.Text = "Success!";

                        this.btnSubmit.Enabled = true;

     

                    }

                    else

                    {

                        this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",

                              "<script language='javascript'>alert('File type is not right!');</script>");

                    }

                }

            }

            else

            {

                this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",

                       "<script language='javascript'>alert('The uploaded file is not a image file!');</script>");

            }

        }

    }

     

    相关贴子:

    http://forums.asp.net/p/1051895/2171502.aspx

     

     

    3.5 如何使File Upload 控件和UpdatePanel协同工作?  [回到顶端]

     

    FileUpload 控件不以异步方式回传,因此不能在AJAX UpdatePanel的内部运行。

     

    使FileUploadAjax UpdatePanel内部工作的技巧是在UpdatePanel 内设置回传触发器。

     

    样例代码:

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

    <Triggers >

    <asp:PostBackTrigger ControlID ="Button1" />

    </Triggers>

    <ContentTemplate >

    <asp:FileUpload ID ="fileupload1" runat ="server" /><br />    

    <asp:Button ID ="Button1" runat ="server" Text ="Upload" OnClick="Button1_Click" /><br />

    <asp:Label ID ="Lable1" runat ="server"  Text =""></asp:Label>

    <asp:LinkButton ID ="LinkButton1" runat="server" Text ="Click Here" OnClick="LinkButton1_Click"></asp:LinkButton>

    </ContentTemplate>

    </asp:UpdatePanel>

     

    相关帖子:

    http://forums.asp.net/p/1105208/1689084.aspx

     


    If you have any feedback on this FAQ please send it to fbmsdn@microsoft.com
    2009年7月21日 7:36
  •  

    4.Calendar  [回到顶端]

     

    4.1 如何改变Calendar的文化设定?  [回到顶端]

     

    Calendar.aspx.cs:

    private void Page_Load(object sender, System.EventArgs e)

    {

        System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("ens");

        System.Threading.Thread.CurrentThread.CurrentCulture = culture;

        System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

    }

     

    相关帖子:

    http://forums.asp.net/t/1133896.aspx

     

     

    4.2 如何在Code-Behind中选择多个非连续的日期?  [回到顶端]

     

    调用控件的SelectedDates集合的成员函数‘Add’。你可以以任何顺序添加日期, 因为集合将自动地为你按次序安排它们。

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)

    {

        Calendar1.SelectedDates.Clear();

        Calendar1.SelectedDates.Add(new DateTime(2008, 8, 1));

        Calendar1.SelectedDates.Add(new DateTime(2008, 8, 7));

        Calendar1.SelectedDates.Add(new DateTime(2008, 8, 15));   

    }

     

    相关帖子:

    http://forums.asp.net/t/1260917.aspx

     

     

    4.3 如何在Calendar控件中禁用一些日期?  [回到顶端]

     

    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)

    {

        string date="02/01/2008";

        DateTime dt = DateTime.Parse(date);

        if (e.Day.Date == dt)

            e.Day.IsSelectable = false;

    }

     

    相关帖子:

    http://forums.asp.net/t/1230073.aspx

    How to: Customize Individual Days in a Calendar Web Server Control

     

     

    4.4 如何为服务器端验证扩展Calendar控件?  [回到顶端]

     

    参见:

    http://support.microsoft.com/default.aspx?scid=kb;en-us;310145 

     

     

    4.5 如何在Calendar控件的DayRender事件中设置ToolTips links  [回到顶端]

     

    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)

    {

        e.Cell.Controls.Clear();

        HyperLink link = new HyperLink();

        link.Text = e.Day.Date.Day;

        link.ToolTip = "anything you want here!";

        link.NavigateUrl = url;

        e.Cell.Controls.Add(link);

    }

     

    相关帖子:

    http://forums.asp.net/p/1036174/1800067.aspx

     

     

    4.6 如何让一些日期有不同的外观?  [回到顶端]

     

    我们可以用下面的代码去做:

    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)

    {

        if (e.Day.Date.Month == 2 && e.Day.Date.Day == 25)

        {

            e.Cell.BackColor = System.Drawing.Color.Yellow;

        }

        if (e.Day.Date.DayOfWeek == DayOfWeek.Friday || e.Day.Date.DayOfWeek == DayOfWeek.Saturday)

        {

            e.Cell.Controls.Clear();

            e.Cell.Text = "today isweekend";

        }

    }

     

    相关帖子:

    http://forums.asp.net/p/1036174/1800067.aspx

    How to: Customize Individual Days in a Calendar Web Server Control

    How to: Format Calendar Web Server Control Elements Using Styles

     

     

    5.列表控件  [回到顶端]

     

    5.1 如何使ASP.NET DropDownList支持OptionGroup  [回到顶端]

     

    我们可以重写DropDownList的函数, 为它添加额外的属性。

     

    这是一些关于此问题的好文章。参见:

    http://www.codeproject.com/KB/custom-controls/xlist.aspx 

    http://www.codeproject.com/KB/custom-controls/DropDownListOptionGroup.aspx

     

     

    5.2 如何在DropDownList中禁用一个 item  [回到顶端]

     

    <asp:DropDownList ID="DropDownList1" runat ="server" Width="235px" AutoPostBack="False">

        <asp:ListItem>1</asp:ListItem>

        <asp:ListItem>2</asp:ListItem>

        <asp:ListItem>3</asp:ListItem>

        <asp:ListItem>4</asp:ListItem>

    </asp:DropDownList>

     

    protected void Page_Load(object sender, EventArgs e)

    {

        DropDownList1.Attributes.Add("onchange", "change();");

    }

     

    <script type ="text/javascript" >

          function change()

          {

             var dd=document.getElementById ('<%=DropDownList1.ClientID %>');

             var value=dd.options[dd.selectedIndex].value;

             if(value!="2") //supose you want to disable the item numbered 2

             {

                setTimeout("__doPostBack('DropDownList1','')", 0);

             }

           }

    </script>

     

    相关帖子:

    http://forums.asp.net/p/1041568/1451492.aspx 

     

     

    5.3 如何为DropDownList维持选中的值?  [回到顶端]

     

    你应当放置dropdownlist 的数据绑定代码到!page.Ispostback块中。

     

    !postback 块确保在回传期间它只被填充一次。

    if(!Page.IsPostBack)

    {

        //bind template drop down here

    }

     

    相关帖子:

    http://forums.asp.net/p/1251081/2312321.aspx

     

     

    6.用户控件

     

    6.1 如何添加一个新的属性到UserControl  [回到顶端]

      

    你可以在user control 的位于.ascx.cs的类定义中添加新的属性。例如:

     

    ascx file,

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

     

    ascx.cs 文件,

    public partial class WebUserControl : System.Web.UI.UserControl

    {

        String text2 = String.Empty;

        public String Text

        {

            get

            {

                return Label1 .Text ;

            }

            set

            {

                Label1 .Text  = value;

            }

        }

        public String Text2

        {

            get

            {

                return text2;

            }

            set

            {

                text2 = value;

            }

        }

        protected void Page_Load(object sender, EventArgs e)

        {

            TextBox1.Text = text2;

        }

    }

     

    aspx file

    <%@ Register src="WebUserControl.ascx" mce_src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>

    <uc1:WebUserControl id="WebUserControl1" runat="server" Text="Hello world" Text2="Hello world.">

    </uc1:WebUserControl>

     

    相关贴子:

    http://forums.asp.net/t/349580.aspx

     

     

    6.2 如何访问动态创建的UserControl  [回到顶端]

     

    你可以通过FindControl方法获得用户控件中目标子控件的引用,然后就像使用其它控件一样去使用它。

     

    例子:

    UC.ascx,

    <%@ Control Language="C#" ClassName="UC" %>

    <script runat="server">

    </script>

    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

     

    Page.aspx:

    <%@ Page Language="C#" %>

    <%@ Register src="UC.ascx" tagname="UC" tagprefix="uc1" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        protected void btnLoad_Click(object sender, EventArgs e)

        {

            UC uc = new UC();

            uc.LoadControl("~/uc/UC.ascx");

            uc.ID = "MyUC";

            form1.Controls.Add(uc);

            (form1.FindControl("MyUC").FindControl("txtName") as TextBox).Text = "ASP.NET";

        }

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <title>User Control Demo</title>

    </head>

    <body>

        <form id="form1" runat="server">

        <div>

            <asp:Button ID="btnLoad" runat="server" Text="Loading user control ..."

                onclick="btnLoad_Click" />

        </div>

        </form>

    </body>

    </html>

     

     

    6.3 如何在UserControl内部访问控件?  [回到顶端]

     

    假设这儿有一个命名为UC的用户控件,并且在它的内部仅有一个TextBox控件。现在拖放这个用户控件到web page,你可以使用下面的代码访问TextBox控件。

     

    ((TextBox)UC1.FindControl("TextBox1")).Text = "demo";

     

    要了解基本的原理,请参考INamingContainer:

    http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx

     


    If you have any feedback on this FAQ please send it to fbmsdn@microsoft.com
    2009年7月21日 7:37
  •  

    7.动态控件  [回到顶端]

     

    7.1 如何创建动态control  [回到顶端]

     

    我们可以在Page_Init()Page_Load()事件中动态创建控件,

     

    protected void Page_Load(object sender, EventArgs e)

    {

        TextBox dynamicTextBox = new TextBox();

        dynamicTextBox.ID = "DynamicTextBox";

        dynamicTextBox.AutoPostBack = true;

        dynamicTextBox.Text = "InitData";

        dynamicTextBox.TextChanged += new EventHandler(dynamicTextBox_TextChanged);

        this.Form.Controls.Add(dynamicTextBox);

    }

    void dynamicTextBox_TextChanged(object sender, EventArgs e)

    {

        Response.Write("hello");

    }

     

    相关帖子:

    http://forums.asp.net/t/1152363.aspx

     

     

    7.2 如何在动态创建的 TextBox 控件中访问用户输入的值?  [回到顶端]

     

    a.从窗体的POST数据中获得值,下面是代码:

    if(Request.Form["dynamicTextBox"] != null)

        selectedValue = Request.Form["dynamicTextBox"].ToString();

     

    b.通过在webpage中找到控件获得值。

    TextBox txt=this.form1.FindControl("dynamicTextBox") as TextBox;

     

    参见完整样例代码,

    <%@ Page Language="C#" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">

        public string Res = string.Empty;

        protected void Page_Load(object sender, EventArgs e)

        {

            TextBox dynamicTextBox = new TextBox();

            dynamicTextBox.ID = "dynamicTextBox";

            form1.Controls.Add(dynamicTextBox);

        }

        protected void btnForm_Click(object sender, EventArgs e)

        {

            lblMsg.Text += "<br /> Form way:";

            if (Request.Form["dynamicTextBox"] != null)

                Res = Request.Form["dynamicTextBox"].ToString();

            lblMsg.Text += Res;

        }

        protected void btnFindControl_Click(object sender, EventArgs e)

        {

            lblMsg.Text += "<br /> FindControl way: ";

            TextBox dynamicTextBox = this.form1.FindControl("dynamicTextBox") as TextBox;

            Res = dynamicTextBox.Text;

            lblMsg.Text += Res;

        }

    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <title>Demo</title>

    </head>

    <body>

        <form id="form1" runat="server">

        <div>

            <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>

            <asp:Button ID="btnForm" runat="server" Text="Form Way" OnClick="btnForm_Click" />

            <asp:Button ID="btnFindControl" runat="server" Text="FindControl Way" OnClick="btnFindControl_Click" />

        </div>

        </form>

    </body>

    </html>

     

    相关贴子:

    http://forums.asp.net/p/1119972/1745762.aspx 

     

     

    7.3 通过JavaScript访问动态控件?  [回到顶端]

     

    Javascript中引用控件的ClientID属性(UniqueID)

    protected void Page_Load(object sender, EventArgs e)

    {

        Button btn= new Button();

        btn.ID = "btn5";

        btn.Attributes.Add("runat", "server");

        btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");

        btn.Text = "Test";

        this.form1.Controls.Add(btn);

    }

    function pop(InputBoxID)

    {

       var InputControl = document.getElementById(InputBoxID);

       alert(InputControl.value);

    }

     

    或者使用下面的方法。

    btn.Attributes.Add("onclick", "pop(this)");

    function pop(InputBox)

    {

       alert(InputBox.value);

    }

     

    相关帖子:

    http://forums.asp.net/p/1239593/2260331.aspx#2260331

     

     

    7.4 在回传后如何动态的保留所有已添加的服务器控件?  [回到顶端]

     

    你应该在Page_loadPage_init()函数中每次重新创建这些动态控件。

    protected void Page_Load(object sender, EventArgs e)

    {

        //recreate these dynamic control.

    }

     

    相关贴子:

    http://forums.asp.net/p/1242809/2280514.aspx 

     

     

    7.5 为何在回传后动态创建的控件消失  [回到顶端]

     

    由于在每一次回传后,动态的button都必须重新创建,因此移除if(!Page.IsPostBack)。如果你能在Page事件中创建控件,这可能会更好。

     

    相关贴子:

    http://forums.asp.net/p/1080863/1598618.aspx

     

     

    8.样式  [回到顶端]

     

    8.1 如何在Code-Behind中使用?  [回到顶端]

     

    Label1.Attributes.Add("style", "background-color:Red");

     

     

    8.2 如何在JavaScript中使用?  [回到顶端]

     

    document.getElementById("Label1").style.backgroundColor = "Red";

     

     

    8.3 如何移除空格?  [回到顶端]

     

    添加下面的代码到“head”标签内

    <style type="text/css">

    body

    {

        padding: 0px;

        margin: 0px;

    }

    </style>

     

     

    8.4 如何和html一起使用?  [回到顶端]

     

    <link href="<%= CSS %>" rel="stylesheet" type="text/css" />

     

    注意: CSS是极其有价值的

    Linked style sheet 通常位于<head>标签中,但是如果它被放到<body>标签内也不必担心。同时, <head>标签必须有runat=”server” 属性。

     

    相关帖子:

    http://forums.asp.net/p/1197909/2076464.aspx 

     

     

    8.5 如何把image设置为Button的背景?  [回到顶端]

     

    <input name="Submit" type="button" value="" style="border-style: none; background-color: Transparent; background-image: url('bg.png'); width: 68px; height: 20px; vertical-align: middle;" />

     

    相关贴子:

    http://forums.asp.net/t/299555.aspx

     

     

    8.6 如何为ListBoxitems着色?  [回到顶端]

     

    示例代码:

    <style type="text/css">

    .optred{background-color:red;}

    .optblue{background-color:blue;}

    </style>

     

    protected void Page_PreRender(object sender, EventArgs e)

    {

        bool flag=false;

        foreach (ListItem li in ListBox1.Items)

        {

            if (flag)

            {

                li.Attributes.Add("class", "optred");

                flag = false;

            }

            else

            {

                li.Attributes.Add("class", "optblue");

                flag = true;

            }

        }

    }

     

    请参见:

    http://www.codeproject.com/KB/webforms/ColorListBox.aspx 

     


    If you have any feedback on this FAQ please send it to fbmsdn@microsoft.com
    2009年7月21日 7:38
  •  

    9.打印  [回到顶端]

     

    9.1 如何用CSS去打印web page的一部分?  [回到顶端]

     

    CSS代码:

    <style media="print">

            .Noprint

            {

                display: none;

            }

            .Print

            {

                page-break-after: always;

            }

    </style>

     

    HTML代码:

    <div class="Noprint">

         I am not print;

    </div>

    <div class="Print">

         I will print;

    </div>

     

    相关帖子:

    http://forums.asp.net/t/981539.aspx

     

     

    9.2 如何通过JavaScript去打印web page的一部分(1)  [回到顶端]

     

    JavaScript代码:

    <script language="JavaScript" type="text/JavaScript">

            function doPrint() {

            bdhtml=window.document.body.innerHTML;

            sprnstr="<!--startprint-->";

            eprnstr="<!--endprint-->";

            prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);

            prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));

            window.document.body.innerHTML=prnhtml;

            window.print();

            }

    </script>

     

    HTML代码:

    <!--startprint-->

    This area will print!

    <!--endprint-->

    <br />

    I will not print?

    <input id="btnPrint" type="button" value="Print" onclick="doPrint()" />

     

    相关帖子:

    http://forums.asp.net/p/1234564/2256428.aspx

     

     

    9.3 如何通过JavaScript去打印web page的一部分(2)  [回到顶端]

     

    JavaScript代码:

    <script language="javascript" type="text/javascript">

        function printdiv(divID)

        {

          var headstr = "<html><head><title></title></head><body>";

          var footstr = "</body>";

          var newstr = document.all.item(divID).innerHTML;

          var oldstr = document.body.innerHTML;

          document.body.innerHTML = headstr+newstr+footstr;

          window.print();

          document.body.innerHTML = oldstr;

          return false;

        }

    </script>

     

    HTML代码:

    <input name="b_print" type="button" onclick="printdiv('divID');" value=" Print " />

    <div id="divID">

    <h1 style="color:green">

    The Div content which you want to print</h1>

    </div>

     

    相关帖子:

    http://forums.asp.net/t/1263912.aspx

     

     

    10.邮件  [回到顶端]

     

    10.1 ASP.NET中哪些类被使用去发送e-mails  [回到顶端]

     

    MailMessageSmtpMailASP.NET应用程序中被用于发送emailsMailMessage SmtpMail来自于NET Framework 1.1 类库中的System.Web.Mail命名空间。并且,假若你已经安装了.NET Framework 2.0,你可以使用System.Net.Mail来代替System.Web.Mail

     

     

    10.2 如何通过使用System.Net.Mail发送 emails  [回到顶端]

     

    CODE-BEHIND:

    MailMessage message = new MailMessage();

    message.From = new MailAddress("fromusername@DomainName");

    message.To.Add(new MailAddress("tousername@DomainName"));

    message.CC.Add(new MailAddress("ccusername@DomainName"));

    message.Subject = "Subject";

    message.Body = "Content";

    SmtpClient client = new SmtpClient();

    client.Send(message);

     

    web.config:

    <system.net>

        <mailSettings>

            <smtp from="username@DomainName">

                <network host="SMTPServerName" port="25" userName="username" password="secret" defaultCredentials="true" />

            </smtp>

        </mailSettings>

    </system.net>

     

    相关帖子:

    http://forums.asp.net/t/971802.aspx

     

     

    10.3 如何配置SMTP服务器?  [回到顶端]

     

    IIS为例,请查阅下面的链接:

    http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/56c94d38-b10f-4a1b-a1cd-3714387a042a.mspx?mfr=true

    http://www.codeproject.com/KB/winsdk/ConfigServerSmtp.aspx

     

     

    10.4 如何用Gmail服务器发送email  [回到顶端]

     

    请首先阅读FAQ “How to send email by using System.Net.Mail?”。请注意当配置接下来的设置时你需要知道下面几点:

    ·SMTP服务器名

    ·端口号

    ·SSL认证

     

    Gmail SMTP 服务器名是“smpt.gmail.com”;

    Gmail 端口是465, 并非默认端口25;

    SSL 认证应当设置为true;

     

    因此通过Gmail成功发送邮件的秘诀是:端口465,服务器名“smtp.gmail.com”SSL = true

     

    相关贴子:

    http://forums.asp.net/p/1167140/1944223.aspx

    http://forums.asp.net/p/1234241/2235990.aspx

     


    If you have any feedback on this FAQ please send it to fbmsdn@microsoft.com
    2009年7月21日 7:39