灵魂腐蚀 发表于 2015-1-16 22:29:23

ASP编程:一个ASP.NET+XML留言本例子

结论:和PHP一样,ASP简单而易于维护,很适合小型网站应用,通过DCOM和MTS技术,ASP甚至还可以完成小规模的企业应用,但ASP的致命缺点就是不支持跨平台的系统,在大型项目开发和维护上非常困难。viewpost.aspx--观察提交的留言
viewguestbook.aspx--观察一切留言
Header.inc
guestpost.aspx--留言表单及XML写操纵
Footer.inc
Guest.xml--XML数据

源代码以下:

viewguestbook.aspx
<%@ImportNamespace="System"%>
<%@ImportNamespace="System.IO"%>
<%@ImportNamespace="System.Data"%>
<%@AssemblyName="System.Xml"%>
<%@ImportNamespace="System.Xml"%>
<%@PageLanguage="C<%--NeededAssembiles--%>

<html>
<head>
<title>WelcometoSaurabhsGuestBook.</title>
<scriptlanguage="C//runthescriptwhenthePageisLoaded
publicvoidPage_Load(Objectsender,EventArgse)
{
//anlabel,itsusestatedlater
tryagain:

//thepathtotheXmlfilewhichwillcontainallthedata
//modifythisifyouhaveanyotherfileordirectorymappings.
//modifythisifyouhavebeendirectedherefromStep2oftheReadMefile.
stringdatafile="db/guest.xml";

//try-CatchblocktoreadfromanXMLfile
try
{
//makeaninstancetotheXMLDataDocumentclass
//thisclasscanreadfromanxmlfileinandorderedformat
XmlDataDocumentdatadoc=newXmlDataDocument();

//InfertheDataSetschemafromtheXMLdataandloadtheXMLData
datadoc.DataSet.ReadXml(newStreamReader(Server.MapPath(datafile)));

//DatabindthefirsttableintheDatasettotheRepeter
MyDataList.DataSource=datadoc.DataSet.Tables.DefaultView;
MyDataList.DataBind();

//freeuptheXMLfiletobeusedbyotherprograms
datadoc=null;


}
catch(IOExceptioned)
{
//HereIamfornowtryingtoovercomeabuginmyguestbookexapmle
//theBugisthatonlyoneclasscaneitherreadorwritetomyXML
//datafileatatime.
//Ifthefileisbeingusedmysomesomeotherpage(egtheguestbookviewingpage)
//thenanIOExceptionwillbethrown
//Sotohandlesuchsitutationswhatwedoisthat
//IfanIOExceptionisthrownthepagegoesagaintothetryagainlabel
//andtriestowriteagainintothexmlfile
//thisgoesontillfinallytheresourceisfreedandthexmlfileiswrittento.

gototryagain;
}
catch(Exceptionedd)
{
//catchanyotherexceptionsthatoccur
errmess.Text="CannotreadfromXMLfilebecause"+edd.ToString();
}



}


</script>
<LINKhref="mystyle.css"type=text/cssrel=stylesheet>

</head>
<bodytopmargin="0"leftmargin="0"marginwidth="0"marginheight="0"rightmargin="0">
<!--<asp:labelid="errmess"text=""style="color:<br>
<h3align="center"class="newsbody">MyGuestbook.</h3>
<ASP:Repeaterid="MyDataList"runat="server">

<templatename="headertemplate">

<tableclass="mainheads"width="100%"style="font:8ptverdana">
<trstyle="background-color:<th>
Name
</th>
<th>
Country
</th>
<th>
Email
</th>
<th>
Comments
</th>
<th>
Date/Time
</th>
</tr>

</template>

<templatename="itemtemplate">

<trstyle="background-color:<td>
<%</td>
<td>
<%</td>
<td>
<%</td>
<td>
<%</td>
<td>
<%</td>
</tr>

</template>

<templatename="footertemplate">

</table>

</template>

</ASP:Repeater>

<!--</body>
</html>


viewpost.aspx
<%@ImportNamespace="System"%>
<%@PageLanguage="C<html>
<head>
<title>WelcometoSaurabhsGuestBook.</title>
<scriptlanguage="C//executethisscriptwhenthepageloads
voidPage_Load(ObjectSrc,EventArgsE)
{
//ifthepageiscalledfromanothepage
if(!Page.IsPostBack){
//getthediffrentParametersfromthequerrystringandstoreit
//torespectiveLabels
NameLabel.Text=Request.Params["Name"];
CountryLabel.Text=Request.Params["Country"];
EmailLabel.Text=Request.Params["Email"];
CommentsLabel.Text=Request.Params["Comments"];
}
if(Page.IsPostBack)
{
//elsedisplayanerror
errmess.Text="ThisPageCannotbecalleddirectly.IthastobecalledfromtheGuestbookpostingpage.";
}
}
</script>
<LINKhref="mystyle.css"type=text/cssrel=stylesheet>
</head>
<bodytopmargin="0"leftmargin="0"rightmargin="0"marginwidth="0"marginheight="0">
<!--<asp:labelid="errmess"text=""style="color:<center>
<h2class="newsbody"><b>ThankYou,forpostinginMyGuestBook.</b></h2>
<tablealign=centerwidth="60%"border="0"cellspacing="2"cellpadding="1">
<trclass="titheading"><tdcolspan="2">TheinformationYouPosted!</td></tr>
<trclass="newsbody">
<td>Name:</td>
<td><asp:labelid="NameLabel"text=""runat="server"/></td>
</tr>
<trclass="newsbody">
<td>Country:</td>
<td><asp:labelid="CountryLabel"text=""runat="server"/></td>
</tr>
<trclass="newsbody">
<td>E-mail:</td>
<td><asp:labelid="EmailLabel"text=""runat="server"/></td>
</tr>
<trclass="newsbody">
<td>Comments:</td>
<td><asp:labelid="CommentsLabel"text=""runat="server"/></td>
</tr>
</table>
<br>
<h4class="newsbody"><ahref="viewguestbook.aspx">Clickhere</a>toviewGuestBook.</h4><br>
</center>
<!--
</body>
</html>


guestpost.aspx

<%@ImportNamespace="System"%>
<%@PageLanguage="C<%@ImportNamespace="System.IO"%>
<%@AssemblyName="System.Xml"%>
<%@ImportNamespace="System.Xml"%>
<%--Thesearetheimportedassembilesandnamespacesneedtoruntheguestbook--%>

<html>

<head>
<title>WelcometoSaurabhsGuestBook.</title>
<scriptLanguage="C///<summary>
///Thismethordiscalledwhenthesubmitbuttonisclicked
///</summary>
publicvoidSubmit_Click(Objectsender,EventArgse)
{
//Alabelneedtothegotostatementexplainedbelow
tryagain:

//thepathtotheXmlfilewhichwillcontainallthedata
//modifythisifyouhaveanyotherfileordirectorymappings.
//modifythisifyouhavebeendirectedherefromStep2oftheReadMefile.
stringdatafile="db/guest.xml";

//putthepostingcodewithinaTry-Catchblock
try{

//proceedonlyifalltherequiredfeildsarefilled-in
if(Page.IsValid&&Name.Text!=""&&Country.Text!=""&&Email.Text!=""){

errmess.Text="";

//makeaninstanceoftheclassXmlDocument
XmlDocumentxmldocument=newXmlDocument();

//loadthexmlfileyouwilluseasyourdatabase.
//SinceweareworkingonaserverwehavetouseServer.MapPath()
//tomapethepathtothedatabasefile

xmldocument.Load(Server.MapPath(datafile));

//makeaninstanceofDocumentNavigatorclasswhichwillhelpusto
//navigateintheloadedXMLdatafile.
DocumentNavigatornavigator=newDocumentNavigator(xmldocument);

//belowcodeisverysignificantasitnavigatesthroughtheXMLdocumentand
//storestherequiredvalues(ps:readthiscodecarefully)

//firstmovetothexmldocumentselements(inmyxmlfilethiswillcometotheGuestsNode
navigator.MoveToDocumentElement();

//theninsertFirstelement(FirstChild)whichwillcontainalltheinformation
//ofasingleguestposting
navigator.Insert(TreePosition.FirstChild,XmlNodeType.Element,"Guest","","");

//InserttheElementofNameastheFirstnodeofGuest
navigator.Insert(TreePosition.FirstChild,XmlNodeType.Element,"Name","","");
//ThisisimportanttospecifywhatkindofValuewilltheNameelementcontain
navigator.Insert(TreePosition.FirstChild,XmlNodeType.Text,"Name","","");
//assigntheNameelementtheValuefromthe.TextpropertyoftheTextBox
navigator.Value=Name.Text;

//GobacktotheParentNodeieGuest
navigator.MoveToParent();

//InsertanotherElementCountryAftertheFirstChildie.aftertheNamenode.
navigator.Insert(TreePosition.After,XmlNodeType.Element,"Country","","");
navigator.Insert(TreePosition.FirstChild,XmlNodeType.Text,"Country","","");
navigator.Value=Country.Text;

navigator.MoveToParent();
navigator.Insert(TreePosition.After,XmlNodeType.Element,"Email","","");
navigator.Insert(TreePosition.FirstChild,XmlNodeType.Text,"Email","","");
navigator.Value=Email.Text;

navigator.MoveToParent();
navigator.Insert(TreePosition.After,XmlNodeType.Element,"Comments","","");
navigator.Insert(TreePosition.FirstChild,XmlNodeType.Text,"comments","","");
navigator.Value=Comments.Value;
navigator.MoveToParent();

navigator.Insert(TreePosition.After,XmlNodeType.Element,"DateTime","","");
navigator.Insert(TreePosition.FirstChild,XmlNodeType.Text,"DateTime","","");
//settheDatetimestampoftheentry
DateTimenow=DateTime.Now;
navigator.Value=now.ToShortDateString()+""+now.ToShortTimeString();

//aftermakingthenecessarychangesweSavethechengestotheXmlDocument
xmldocument.Save(Server.MapPath(datafile));
//freeuptheXMLfilefromtheDocumentfilesothatotherprogramscanuseit
xmldocument=null;

//Buildacustomquerrysendingthedatapostedtoanotherpagefordisplay
//sinceitisaquerrywehavetoencodeitinUTF8format
StringQueryString="Name="+System.Web.HttpUtility.UrlEncodeToString(Name.Text,System.Text.Encoding.UTF8);
QueryString+="&&Country="+System.Web.HttpUtility.UrlEncodeToString(Country.Text,System.Text.Encoding.UTF8);
QueryString+="&&Email="+System.Web.HttpUtility.UrlEncodeToString(Email.Text,System.Text.Encoding.UTF8);
QueryString+="&&Comments="+System.Web.HttpUtility.UrlEncodeToString(Comments.Value,System.Text.Encoding.UTF8);

//gotothepageviewpost.aspxandappendthequerrystringatitsend.
Page.Navigate("viewPost.aspx?"+QueryString);

}
else
{
//ifanyoftheFeildsarekeptemptyshowanerrormessage
errmess.Text="FillinalltherequiredfeildsoftheGuestbook.";

}
}
catch(IOExceptioned)
{
//HereIamfornowtryingtoovercomeabuginmyguestbookexapmle
//theBugisthatonlyoneclasscaneitherreadorwritetomyXML
//datafileatatime.
//Ifthefileisbeingusedmysomesomeotherpage(egtheguestbookviewingpage)
//thenanIOExceptionwillbethrown
//Sotohandlesuchsitutationswhatwedoisthat
//IfanIOExceptionisthrownthepagegoesagaintothetryagainlabel
//andtriestowriteagainintothexmlfile
//thisgoesontillfinallytheresourceisfreedandthexmlfileiswrittento.
gototryagain;
}
catch(Exceptionedd)
{
//catchanyotherexceptionthatoccur
errmess.Text="CannotwritetoXMLfilebecause"+edd.ToString();

}
}
</script>
<LINKhref="mystyle.css"type=text/cssrel=stylesheet>
</head>
<bodytopmargin="0"leftmargin="0"rightmargin="0"marginwidth="0"marginheight="0">
<%--Includeaheaderfileheader.inc--%>
<!--<br>
<h3align="center"class="newsbody">GuestbookPostPage.</h3>
<br>
<asp:labelid="errmess"text=""style="color:<formrunat="server">
<tableborder="0"width="80%"align="Center">
<tr>
<tdclass="newsheading"><b>Sign-inMyGuestBook</b></td>
<tdclass="newsheading"></td>

</tr>
<trclass="newsbody">
<td>Name:</td>
<td><asp:textboxtext=""id="Name"runat="server"/><fontcolor=
</tr>
<trclass="newsbody">
<td>Country:</td>
<td><asp:textboxtext=""id="Country"runat="server"/><fontcolor=
</tr>
<trclass="newsbody">
<td>E-Mail:</td>
<td><asp:textboxtest=""id="Email"runat="server"/><fontcolor=
</tr>
<trclass="newsbody">
<td>Comments:</td>
<td><textareaid="Comments"cols="25"rows="4"runat="server"/></td>

</tr>
<trclass="newsbody">
<tdcolspan="2">
<asp:Buttonclass="newsheading"id="write"Text="Submit"runat="server"/></td>

</tr>
</table>
</form>
<br>
<h4class="newsbody"><ahref="viewguestbook.aspx">Clickhere</a>toviewGuestBook.</h4><br>
<!--</body>
</html>
ASP是依赖组件的,能访问数据库的组件好多就有好多种,再有就是你微软的工具可是什么都要收钱的啊!

小魔女 发表于 2015-1-25 08:45:44

它可通过内置的组件实现更强大的功能,如使用A-DO可以轻松地访问数据库。

爱飞 发表于 2015-2-2 20:12:56

ASP也是这几种脚本语言中最简单易学的开发语言。但ASP也是这几种语言中唯一的一个不能很好支持跨平台的语言。  因为ASP脚本语言非常简单,因此其代码也简单易懂,结合HTML代码,可快速地完成网站的应用程序。

再现理想 发表于 2015-2-8 04:57:25

接下来就不能纸上谈兵了,最好的方法其实是实践。实践,只能算是让你掌握语言特性用的。而提倡做实际的Project也不是太好,因为你还没有熟练的能力去综合各种技术,这样只能使你自己越来越迷糊。

仓酷云 发表于 2015-2-24 06:45:40

用户端的浏览器不需要提供任何别的支持,这样大提高了用户与服务器之间的交互的速度。

深爱那片海 发表于 2015-3-7 11:54:09

Application:这个存储服务端的数据,如果不清除,会直到web应用程序结束才清除(例如重启站点)

金色的骷髅 发表于 2015-3-15 04:13:13

下面简单介绍一下我学习ASP的方法,希望对想学习ASP的朋友有所帮助...

海妖 发表于 2015-3-21 18:08:24

Response:从字面上讲是“响应”,因此这个是服务端向客户端发送东西的,例如Response.Write
页: [1]
查看完整版本: ASP编程:一个ASP.NET+XML留言本例子