按月存档: 08月 2008

ASP.NET 如何取得 Request URL 的各个部分

我們在開發網頁應用程式,時常需要去解析網址(Request.Url)的每個片段,進行一些判斷。例如說 "http://localhost:1897/News/Press/Content.aspx/123?id=1#toc",我們想要取得網址裡第一層目錄的名字(News)用以判斷不同的頁面標題(Page Title)。
我看很多人都用字串的 IndexOf 方法與 Substring 方法:

Request.Url.PathAndQuery.Substring(1, Request.Url.PathAndQuery.IndexOf("/", 1)-1)

這實在太埋沒 .NET 的強大設計了,事實上在 Request 物件就已經提供很多方便的屬性(Property)可供取得網址的片段。
底下這張表就是各種跟 Browser Request 的網址相關的屬性與用法:

網址:http://localhost:1897/News/Press/Content.aspx/123?id=1#toc

Request.ApplicationPath
/

Request.PhysicalPath
D:\Projects\Solution\web\News\Press\Content.aspx

System.IO.Path.GetDirectoryName(Request.PhysicalPath)
D:\Projects\Solution\web\News\Press

Request.PhysicalApplicationPath
D:\Projects\Solution\web\

System.IO.Path.GetFileName(Request.PhysicalPath)
Content.aspx

Request.CurrentExecutionFilePath
/News/Press/Content.aspx

Request.FilePath
/News/Press/Content.aspx

Request.Path
/News/Press/Content.aspx/123

Request.RawUrl
/News/Press/Content.aspx/123?id=1

Request.Url.AbsolutePath
/News/Press/Content.aspx/123

Request.Url.AbsoluteUri
http://localhost:1897/News/Press/Content.aspx/123?id=1

Request.Url.Scheme
http

Request.Url.Host
localhost

Request.Url.Port
1897

Request.Url.Authority
localhost:1897

Request.Url.LocalPath
/News/Press/Content.aspx/123

Request.PathInfo
/123

Request.Url.PathAndQuery
/News/Press/Content.aspx/123?id=1

Request.Url.Query
?id=1

Request.Url.Fragment
 

Request.Url.Segments
/
News/
Press/
Content.aspx/
123

所以當你看了這張表之後,你還會想用 Request.Url.PathAndQuery.Substring(1, Request.Url.PathAndQuery.IndexOf("/", 1)-1) 這種寫法嗎?
用這樣寫 Request.Url.Segments[1].Replace("/", "") 不是又短又直覺嗎? ^_^
以下是產生以上表格的程式碼:

    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<table cellpadding=3 cellspacing=0 border=1>");
        sb.Append("<tr><td colspan=2>");
        sb.Append("網址:"http://localhost:1897/News/Press/Content.aspx/123?id=1#toc">http://localhost:1897/News/Press/Content.aspx/123?id=1#toc        sb.Append("</td></tr>"); ");
        // Request.ApplicationPath
        sb.Append("<tr><td>");
        sb.Append("Request.ApplicationPath");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.ApplicationPath + "</b>");
        sb.Append("</td></tr>");
        // Request.PhysicalPath
        sb.Append("<tr><td>");
        sb.Append("Request.PhysicalPath");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.PhysicalPath + "</b>");
        sb.Append("</td></tr>");
        // System.IO.Path.GetDirectoryName(Request.PhysicalPath)
        sb.Append("<tr><td>");
        sb.Append("System.IO.Path.GetDirectoryName(Request.PhysicalPath)");
        sb.Append("</td><td>");
        sb.Append("<b>" + System.IO.Path.GetDirectoryName(Request.PhysicalPath) + "</b>");
        sb.Append("</td></tr>");
        // Request.PhysicalApplicationPath
        sb.Append("<tr><td>");
        sb.Append("Request.PhysicalApplicationPath");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.PhysicalApplicationPath + "</b>");
        sb.Append("</td></tr>");
        // System.IO.Path.GetFileName(Request.PhysicalPath)
        sb.Append("<tr><td>");
        sb.Append("System.IO.Path.GetFileName(Request.PhysicalPath)");
        sb.Append("</td><td>");
        sb.Append("<b>" + System.IO.Path.GetFileName(Request.PhysicalPath) + "</b>");
        sb.Append("</td></tr>");
        // Request.CurrentExecutionFilePath
        sb.Append("<tr><td>");
        sb.Append("Request.CurrentExecutionFilePath");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.CurrentExecutionFilePath + "</b>");
        sb.Append("</td></tr>");
        // Request.FilePath
        sb.Append("<tr><td>");
        sb.Append("Request.FilePath");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.FilePath + "</b>");
        sb.Append("</td></tr>");
        // Request.Path
        sb.Append("<tr><td>");
        sb.Append("Request.Path");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Path + "</b>");
        sb.Append("</td></tr>");
        // Request.RawUrl
        sb.Append("<tr><td>");
        sb.Append("Request.RawUrl");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.RawUrl + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.AbsolutePath
        sb.Append("<tr><td>");
        sb.Append("Request.Url.AbsolutePath");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.AbsolutePath + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.AbsoluteUri
        sb.Append("<tr><td>");
        sb.Append("Request.Url.AbsoluteUri");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.AbsoluteUri + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.Scheme
        sb.Append("<tr><td>");
        sb.Append("Request.Url.Scheme");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.Scheme + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.Host
        sb.Append("<tr><td>");
        sb.Append("Request.Url.Host");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.Host + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.Port
        sb.Append("<tr><td>");
        sb.Append("Request.Url.Port");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.Port + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.Authority
        sb.Append("<tr><td>");
        sb.Append("Request.Url.Authority");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.Authority + "</b>");
        sb.Append("</td></tr>");
        // local Request.Url.LocalPath
        sb.Append("<tr><td>");
        sb.Append("Request.Url.LocalPath");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.LocalPath + "</b>");
        sb.Append("</td></tr>");
        // Request.PathInfo
        sb.Append("<tr><td>");
        sb.Append("Request.PathInfo");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.PathInfo + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.PathAndQuery
        sb.Append("<tr><td>");
        sb.Append("Request.Url.PathAndQuery");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.PathAndQuery + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.Query
        sb.Append("<tr><td>");
        sb.Append("Request.Url.Query");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.Query + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.Fragment
        // 原則上你應該無法從 Request.Url.Fragment 取得任何資料,因為通常 Browser 不會送出 #toc 這個部分
        sb.Append("<tr><td>");
        sb.Append("Request.Url.Fragment");
        sb.Append("</td><td>");
        sb.Append("<b>" + Request.Url.Fragment + "</b>");
        sb.Append("</td></tr>");
        // Request.Url.Segments
        sb.Append("<tr>");
        sb.Append("<td>");
        sb.Append("Request.Url.Segments");
        sb.Append("</td>");
        sb.Append("<td>");
        string[] segments = Request.Url.Segments;
        foreach (string s in segments)
        {
            sb.Append("<b>" + s + "</b>");
            sb.Append("<br/>");
        }
        sb.Append("</td>");
        sb.Append("</tr>");
        sb.Append("</table>");
        ltlTable.Text = sb.ToString();
    }

IEWebControls使用介绍

1.下载地址
http://msdn.microsoft.com/downloads/samples/internet/ASP_DOT_NET_ServerControls/WebControls/default.asp
下载后是后缀为bat的版本
(1)bulid.将bulid.bat的路径指向csc.exe所在路径,生成Microsoft.Web.UI.WebControls.dll。
(2)在wwwroot下创建空目录webctrl_client\1_0。
(3)将build\Runtime下的文件拷至webctrl_client\1_0下。
(4)选择工具箱的自定义工具箱,添加Microsoft.Web.UI.WebControls.dll。
有些麻烦
但如果你能找到后缀是msi的自动安装版本,直接下一步就行(我一直用这个版本,hoho)
安装后,通过“自定义工具箱”->“.net框架组件”把TreeView添加到工具箱里
2.运行时无法显示
一般是TreeView的版本问题,最好下载英文版自动安装版本重新安装,安装前应该先到添加删除程序里卸掉原版本
3.显示格式出错(非树状显示)
TreeView要求客户端浏览器版本为IE5.5及以上,最好要求客户端升级为IE6.0
4.框架里使用TreeView
设置NavigateUrl、Target属性,可更新另外的Frame
5.找不到TreeNode类
使用TreeView,最好添加namespace:using Microsoft.Web.UI.WebControls;
6.遍历TreeView节点(递归算法)
private void Page_Load(object sender, System.EventArgs e)
{
 GetAllNodeText(TreeView1.Nodes);
}
void GetAllNodeText(TreeNodeCollection tnc)
{
 foreach(TreeNode node in tnc)
 {
  if(node.Nodes.Count!=0)
   GetAllNodeText(node.Nodes);
  Response.Write(node.Text + " ");
 }
}
7.得到node结点的父节点
TreeNode pnode;
if(node.Parent is TreeNode)
 pnode=(TreeNode)node.Parent;
else
 //node is root node
8.修改TreeView样式(示例)
<iewc:TreeView id="TreeView1" runat="server" HoverStyle="color:blue;background:#00ffCC;" DefaultStyle="background:red;color:yellow;" SelectedStyle="color:red;background:#00ff00;">
用代码:
TreeView1.DefaultStyle["font-size"] = "20pt";
9.展开时不提交,改变选择节点时才提交
将autopostback设置成false; 
在body里添加  <body  onload="initTree()"> 
然后在PageLoad里写: 
string  strTreeName  =  "TreeView1"; 
string  strRef  =  Page.GetPostBackEventReference(TreeView1); 
string  strScript  =  "<script  language=\"JavaScript\">  \n"  +  "<!–  \n"  +  "            function  initTree()  {  \n"  +"                        "  +  strTreeName  +  ".onSelectedIndexChange  =  function()  {  \n"  +    "if  (event.oldTreeNodeIndex  !=   
event.newTreeNodeIndex)  \n"  +  "this.queueEvent(‘onselectedindexchange’,  event.oldTreeNodeIndex  +  ‘,’  +  event.newTreeNodeIndex);  \n"  +    "window.setTimeout(‘"  +  strRef.Replace("’","file://’/")    +  "’,  0,  ‘JavaScript’);  \n"  +    "                        }  \n"  +      "            }  \n"  +    "//  –>  \n"  +  "</script>"; 
Page.RegisterClientScriptBlock("InitTree",strScript  ); 
 
这样就只有你点击的节点更改的时候才提交!
10.TreeView结合XML
把XML文件设置为如下格式,然后直接设置TreeNodeSrc为该XML文件就行
<?xml version="1.0" encoding="GB2312"?>
<TREENODES>
 <TREENODE TEXT="node0" EXPANDED="true">
  <TREENODE TEXT="node1"/>
  <TREENODE TEXT="node2"/>
 </TREENODE>
 <TREENODE TEXT="node3" NavigateURL="3.aspx"/>
</TREENODES>
或者用代码
TreeView1.TreeNodeSrc="a.xml";
TreeView1.DataBind();
 
客户端控制TreeView
http://expert.csdn.net/Expert/topic/1382/1382892.xml
1.设置所选节点,如选中第二个节点
function SetSelNode()
{
 TreeView1.selectedNodeIndex="1";
}
2.得到所选节点的Text,ID或NodeData
function GetAttribute()
{
 alert(TreeView1.getTreeNode(TreeView1.selectedNodeIndex).getAttribute("Text"));
}
替换Text为ID或NodeData,可分别得到所选节点的ID或NodeData
3.修改节点属性,如修改第一个节点的Text
function ModifyNode()
{
 var node=TreeView1.getTreeNode("0");
 node.setAttribute("Text","hgknight");
}
4.得到点击节点
function TreeView1.onclick()
{
 alert(TreeView1.getTreeNode(TreeView1.clickedNodeIndex).getAttribute("Text"));
}
5.添加节点
function AddNode()
{
 var node=TreeView1.createTreeNode();
 node.setAttribute("Text","hgknight");
 TreeView1.add(node);   
}
6.js遍历所有节点
 var AllRootNode=new Array();
 AllRootNode=TreeView1.getChildren();
 AlertNode(AllRootNode);  
 function AlertNode(NodeArray)
 {
  if(parseInt(NodeArray.length)==0)
   return;
  else
  {
   for(i=0;i<NodeArray.length;i++)
   {
    var cNode;
    cNode=NodeArray[i];
    alert(cNode.getAttribute("Text"));
    if(parseInt(cNode.getChildren().length)!=0)
     AlertNode(cNode.getChildren());   
   }
  }
 }
 

IEWebcontrol webctrl_client目录配置

以前在服务器部署IEWebcontrol时,需要装完asp.net站点后,再安装iewebcontrols,比较麻烦。
其实在web.config文件中配置一下就可以了,不需要安装。在<configuration>下添加:
<configSections>
          <section name="MicrosoftWebControls" type="System.Configuration.NameValueSectionHandler, System, System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<MicrosoftWebControls>
     <add key="CommonFiles" value="/website/webctrl_client/1_0" />
</MicrosoftWebControls>

DataGrid 中的"ItemCommand" 事件

ItemCommand是在运行上点击任何形式的Button都会执行的,所以在执行的时候就要判断要执行哪个命令。
比如,我在DataGrid上添加了编辑、更新、取消按钮和选择按钮,选择按钮命令名为“Select”,选择按钮添加事件事ItemCommand事件,当点击编辑按钮时程序会先执行ItemCommand后执行EditCommand,如果不想再点击编辑按钮时执行ItemCommand事件里的语句就要加一个判断,如下:
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
    if(e.CommandName == "Select")
    {
         … …
         //您单击按钮时要执行的代码
    }
}