14.示例解析

做一个相对完整的示例,用来显示公司的招聘、新闻、产品介绍等功能。

1.先在工程中建立完整的文件夹,(Admin为后台管理用文件夹,App_Data是数据库文件夹、BLL为业务逻辑文件夹、css为样式文件夹、DAL为数据操作类文件夹,放置强类型数据集、ErrorPages为错误页文件夹、imgs为图片文件夹、js为调用js,jQuery,CKEditor等的文件夹、Library为要用到的库文件夹、master为母版文件夹、upload为上传文件的文件夹、UserControl为用户自定义控件的文件夹),如下截图:

14.示例解析_第1张图片

2.建立数据表,T_News(新闻). T_Products(产品表), T_ProductsCategory(产品类别表)

3.建立强类型集,新闻中有以下几个方法(分页和显示用):

   14.示例解析_第2张图片 14.示例解析_第3张图片

4.先建立普通的HTML框架页面,即用div等元素先划分出导航、头部、中间等的框架,用css来控件显示的位置,然后再建立母版页,并把框架页面中的主要部分放到母版页form中即可,以下为母版页的html

 

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="SetFront.master.cs" Inherits="企业网站.master.SetFront" %>

<!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></title>
    <link href="../css/default.css" rel="stylesheet" type="text/css" />
    <script src="../js/jquery-1.10.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#navigate li").mouseenter(function () {
                $(this).addClass("active").siblings().removeClass("active");
            });
        });
    </script>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div id="main">
        <div id="header">
            <img src="../imgs/default.gif" />
            <ul id="navigate">
                <li><a href="default.aspx">首    页</a></li>
                <li>公司概况</li>
                <li>公司新闻</li>
                <li><a href="ViewProducts.aspx">产品展示</a></li>
                <li>招贤纳士</li>
                <li>关于我们</li>
            </ul>
        </div>
        <br class="clear" />
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        
        </asp:ContentPlaceHolder>
         <br class="clear" />
        <div id="footer">
          <hr />
          <center>企业网站展播,如有累同请来电。</center>
        </div>
    </div>
    </form>
</body>
</html>

5.css文件内容

 

body {
}

.clear
{
    clear:both;
}
#main
{
    width:950px;
    margin-left:auto;
    margin-right:auto;
}

#navigate
{
    list-style-type:none;
}

#navigate li
{
    float:left;
    margin:3px,3px,3px,3px;
}

#navigate .active
{
    background-color:Red;
}

.validator
{
   color:Red;

}

.more
{
    float:right;
}

.ulwidth
{
    width:200px;
}

.ckeditor
{
}

.ProductFloat
{
    float:left;
}

6.建立首页(带有母版,不是普通的aspx),在显示的地方放上objectdatasource及listview等元素

<%@ Page Title="" EnableViewState="false" Language="C#" MasterPageFile="~/master/SetFront.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="企业网站._default" %>
<%@ OutputCache Duration="10" VaryByParam="none" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:ObjectDataSource ID="odsNews" runat="server" DeleteMethod="Delete" 
        InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" 
        SelectMethod="GetTop10Data" 
        TypeName="企业网站.DAL.DataSetNewsTableAdapters.T_NewsTableAdapter" 
        UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_Id" Type="Int64" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Body" Type="String" />
            <asp:Parameter Name="CreateDate" Type="DateTime" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="Title" Type="String" />
            <asp:Parameter Name="Body" Type="String" />
            <asp:Parameter Name="CreateDate" Type="DateTime" />
            <asp:Parameter Name="Original_Id" Type="Int64" />
        </UpdateParameters>
    </asp:ObjectDataSource>
    <asp:Repeater ID="Repeater1" runat="server" DataSourceID="odsNews">
      <HeaderTemplate><ul class="ulwidth"></HeaderTemplate>
      <ItemTemplate><li><a href='ViewNews.aspx?id=<%#Eval("Id") %>'>><%#Eval("Title") %></a></li></ItemTemplate>
      <FooterTemplate><li><a href="morenews.aspx" class="more">更多</a></li></ul></FooterTemplate>
    </asp:Repeater>
</asp:Content>

14.示例解析_第4张图片

“更多”的功能是另起一页,把所有的新闻分页显示出来如下图,用到了分页功能,是高效分页的那种。

14.示例解析_第5张图片

html:

 

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/master/SetFront.Master"  CodeBehind="morenews.aspx.cs" Inherits="企业网站.morenews" %>


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="js/jquery-1.10.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#go").click(function () {
                var i = $("#pgnumber").val();
                location.href = "morenews.aspx?pg=" + i;
            });
        });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
 <div>
    
        <asp:ObjectDataSource ID="odsnews" runat="server" DeleteMethod="Delete" 
            InsertMethod="Insert" OldValuesParameterFormatString="original_{0}"             
            TypeName="企业网站.DAL.DataSetNewsTableAdapters.T_NewsTableAdapter" 
            UpdateMethod="Update" EnablePaging="True" 
             SelectCountMethod="GetAllNewsData" 
            SelectMethod="GetNewsPageData"
           >
            <DeleteParameters>
                <asp:Parameter Name="Original_Id" Type="Int64" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="Title" Type="String" />
                <asp:Parameter Name="Body" Type="String" />
                <asp:Parameter Name="CreateDate" Type="DateTime" />
            </InsertParameters>
            
            <UpdateParameters>
                <asp:Parameter Name="Title" Type="String" />
                <asp:Parameter Name="Body" Type="String" />
                <asp:Parameter Name="CreateDate" Type="DateTime" />
                <asp:Parameter Name="Original_Id" Type="Int64" />
            </UpdateParameters>
        </asp:ObjectDataSource>
        <asp:ListView ID="lvnews" runat="server" DataKeyNames="Id" 
            DataSourceID="odsnews">
           
           
            <EmptyDataTemplate>
                    没有新闻。                 
            </EmptyDataTemplate>
           
            <ItemTemplate>
              <li><a href='ViewNews.aspx?id=<%#Eval("Id") %>'><%#Eval("Title") %></a></li>
            </ItemTemplate>
            <LayoutTemplate>
                 <ul>
                    <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
                 </ul>
                            
               <asp:DataPager ID="DataPager1" runat="server" QueryStringField="pg">
                                <Fields>
                                   <asp:NumericPagerField ButtonType="Link" />
                                   <asp:TemplatePagerField>
                                      <PagerTemplate>
                                        <input type="text" id="pgnumber"> <input type="button" id="go" value="go" >
                                      </PagerTemplate>
                                   </asp:TemplatePagerField>
                                </Fields>
                            </asp:DataPager>    
            </LayoutTemplate>
           
        </asp:ListView>
    
    </div>
</asp:Content>

7.具体查看某个id的新闻,我们可以用Literal元素来显示,因为它在客户端什么也不会渲染出来

<%@ Page Title="" Language="C#" MasterPageFile="~/master/SetFront.Master" AutoEventWireup="true" CodeBehind="ViewNews.aspx.cs" Inherits="企业网站.ViewNews" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
  <p>
    <center>
      <h1>
         <asp:Literal ID="litTitle" runat="server"></asp:Literal>
      </h1>     
    </center>
    
   </p>
  <p style="float:right">
      <asp:Literal ID="litCreateDate" runat="server" ></asp:Literal>
  </p>
  <br class="clear" />
  <p>
     <asp:Literal ID="litBody" runat="server"></asp:Literal>
     
  </p>
</asp:Content>

14.示例解析_第6张图片

8.分类显示处理

   如果公司产器分类太多,要在页面上显示的时候会产生大量的html代码并且看着很乱,可以建立用户控件页面,在上面放一个Repeater或listView即可,用代码绑定它的数据源即可

   html:

   

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UserControlProducts.ascx.cs" Inherits="企业网站.UserControl.UserControlProducts" %>
<asp:Repeater ID="RepeaterPut" runat="server">
<HeaderTemplate><ol></HeaderTemplate>
<ItemTemplate>
<li onmouseout="this.style.background='White'" onmouseover="this.style.background='Blue'"><a href='ViewProductDetail.aspx?id=<%#Eval("Id") %>'><font style="color:Red;font-size:large; "><%#Eval("Name") %></font></a></li>
</ItemTemplate>
<FooterTemplate></ol></FooterTemplate>
</asp:Repeater>

cs:

 

 public partial class UserControlProducts : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var data = new T_ProductsTableAdapter().GetDataByCategoryId(CategoryId);
                RepeaterPut.DataSource = data;
                RepeaterPut.DataBind();
            }
        }

        public int CategoryId
        {
            get;
            set;
        }
    }

这样我们可以把这个做好的UserControlProducts.ascx拖动到ViewProducts.aspx,用示展示产品,有几个分类就拖动几个用户控件到此页面上

Html:

<%@ Page Title="" Language="C#" MasterPageFile="~/master/SetFront.Master" AutoEventWireup="true" CodeBehind="ViewProducts.aspx.cs" Inherits="企业网站.ViewProducts" %>
<%@ Register src="UserControl/UserControlProducts.ascx" tagname="UserControlProducts" tagprefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="ProductFloat">
      <p>医疗器械</p>
      <uc1:UserControlProducts ID="UserControlProducts2" runat="server" CategoryId="1" />
    </div>

    <div class="ProductFloat">
       <p>电动车</p>
       <uc1:UserControlProducts ID="UserControlProducts3" runat="server" 
            CategoryId="2" />
    </div>
    <div class="ProductFloat">
      <p>火炉</p>
      <uc1:UserControlProducts ID="UserControlProducts1" runat="server" 
            CategoryId="3" />
     </div>
    
</asp:Content>

 在用户控件页面设定了CategoryId来根据产品分类,因此,可以在产品页面中分别设定用户控件所对应的CategoryId值,如此例中医疗器械为1,电动车为2,火炉为3.这些是数据库都已设置好的。

14.示例解析_第7张图片

9. 显示每个产品页面

   14.示例解析_第8张图片

 html:

  

<%@ Page Title="" Language="C#" MasterPageFile="~/master/SetFront.Master" AutoEventWireup="true" CodeBehind="ViewProductDetail.aspx.cs" Inherits="企业网站.ViewProductDetail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:ObjectDataSource ID="odsproducts" runat="server" 
        OldValuesParameterFormatString="original_{0}" SelectMethod="GetDataById" 
        TypeName="企业网站.DAL.DataSetProductTableAdapters.T_ProductsTableAdapter">
        <SelectParameters>
            <asp:QueryStringParameter Name="Id" QueryStringField="Id" Type="Int64" />
        </SelectParameters>
    </asp:ObjectDataSource>
    <asp:ObjectDataSource ID="odsCategory" runat="server" 
        OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" 
        TypeName="企业网站.DAL.DataSetProductTableAdapters.T_ProductsCategoryTableAdapter">
    </asp:ObjectDataSource>
    <asp:FormView ID="FormView1" runat="server" DataKeyNames="Id" 
        DataSourceID="odsproducts">
      
        <ItemTemplate>
           
            <br />
            名称:
            <asp:Label ID="NameLabel" runat="server" Text='<%# Bind("Name") %>' />
            <br />
            类别:
            <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("CategoryId") %>' DataTextField="Name" DataValueField="Id" DataSourceID="odsCategory" Enabled="false">
            </asp:DropDownList>
           
            <br />
            图片:
            <img src='<%#ResolveClientUrl("~/upload/images/"+Eval("PicPath")) %>' runat="Server" />
           
            <br />
            描述:
            <asp:Label ID="DescriptionLabel" runat="server" 
                Text='<%# Bind("Description") %>' />
            <br />
            <a href="ViewProducts.aspx">返回</a>
        </ItemTemplate>
    </asp:FormView>
</asp:Content>

9.管理页面

    1).新闻页分布显示ListNews.aspx

      14.示例解析_第9张图片

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListNews.aspx.cs" Inherits="企业网站.Admin.ListNews" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <a href="EditNews.aspx?action=addnew">发布新闻<asp:ObjectDataSource ID="odsnews" 
            runat="server" DeleteMethod="Delete" EnablePaging="True" 
            OldValuesParameterFormatString="original_{0}" 
            SelectCountMethod="GetAllNewsData" SelectMethod="GetNewsPageData" 
            TypeName="企业网站.DAL.DataSetNewsTableAdapters.T_NewsTableAdapter" 
            EnableCaching="True">
            <DeleteParameters>
                <asp:Parameter Name="Original_Id" Type="Int64" />
            </DeleteParameters>
            
        </asp:ObjectDataSource>
        </a>
        &nbsp;<asp:ListView ID="lvNews" runat="server" DataKeyNames="Id" 
            DataSourceID="odsnews">
           
            
            <EmptyDataTemplate>
                <table runat="server" style="">
                    <tr>
                        <td>
                            未返回数据。</td>
                    </tr>
                </table>
            </EmptyDataTemplate>
            
             <ItemTemplate>
                <tr style="">
                   <td>
                     <asp:Button ID="btnDelete" runat="server" Text="删除" CommandName="Delete" onClientClick='return confirm("你要删除它吗?");' />
                     <a href='EditNews.aspx?action=edit&id=<%#Eval("Id")%>'>编辑</a>
                    <td>
                        <asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
                    </td>                    
                   
                    <td>
                        <asp:Label ID="CreateDateLabel" runat="server" 
                            Text='<%# Eval("CreateDate") %>' />
                    </td>
                   
                </tr>
            </ItemTemplate>
            <LayoutTemplate>
                <table runat="server">
                    <tr runat="server">
                        <td runat="server">
                            <table ID="itemPlaceholderContainer" runat="server" border="0" style="">
                                <tr runat="server" style="">
                                   
                                    <th runat="server">
                                        Title</th>
                                    
                                    <th runat="server">
                                        CreateDate</th>
                                </tr>
                                <tr runat="server" ID="itemPlaceholder">
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr runat="server">
                        <td runat="server" style="">
                            <asp:DataPager ID="DataPager2" runat="server">
                                <Fields>
                                    <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" 
                                        ShowLastPageButton="True" />
                                </Fields>
                            </asp:DataPager>
                        </td>
                    </tr>
                </table>
            </LayoutTemplate>            
            
            
            
            
            
            
        </asp:ListView>
    
    </div>
    </form>
</body>
</html>

     2).新增修改产品页EditNews.aspx

       

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false"  CodeBehind="EditNews.aspx.cs" Inherits="企业网站.Admin.editNews" %>

<!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></title>   
    <script src="js/ckeditor/ckeditor.js" type="text/javascript"></script>
    <link href="../css/default.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table border="0" cellspacing="0" cellpadding="0" width="100%">
        <tr>
            <td>标题</td>
            <td>
                <asp:TextBox ID="txtTitle" runat="server" Width="484px"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                    ControlToValidate="txtTitle" CssClass="validator">*</asp:RequiredFieldValidator>
            </td>
        </tr>

        <tr>
            <td>内容</td>
            <td>
              <asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" CssClass="ckeditor"  
                    ></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                    ControlToValidate="txtBody"  CssClass="validator" >*</asp:RequiredFieldValidator>
            </td>
        </tr>

        <tr>
            <td>
                <asp:Button ID="btnSave" runat="server" Text="保存" onclick="btnSave_Click" />
            </td>
            <td></td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using 企业网站.DAL.DataSetNewsTableAdapters;

namespace 企业网站.Admin
{
    public partial class editNews : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string action = Request["action"];
                if (action == "edit")
                {
                    int id = Convert.ToInt32(Request["id"]);
                    var rowdata = new T_NewsTableAdapter().GetDataById(id).Single();
                    txtTitle.Text = rowdata.Title;
                    txtBody.Text = rowdata.Body;
                }
                else if (action == "addnew")
                {

                }
                else
                {
                    throw new Exception("action错误:" + action);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsValid)
                return;
            string action = Request["action"];
            if (action == "edit")
            {
                int id = Convert.ToInt32(Request["id"]);
                T_NewsTableAdapter adapter = new T_NewsTableAdapter();
                var rowdata = adapter.GetDataById(id).Single();
                rowdata.Title = txtTitle.Text;
                rowdata.Body = txtBody.Text;
                adapter.Update(rowdata);
            }
            else if (action == "addnew")
            {
                new T_NewsTableAdapter().Insert(txtTitle.Text, txtBody.Text, DateTime.Now);
            }
            else
            {
                throw new Exception("action错误:" + action);
            }

            Response.Redirect("~/Admin/ListNews.aspx");
        }
    }
}

    3)产品浏览ListProduct.aspx

       14.示例解析_第10张图片

 

<%@ Page Title="" Language="C#" MasterPageFile="~/master/SetFront.Master" AutoEventWireup="true" CodeBehind="ListProduct.aspx.cs" Inherits="企业网站.Admin.ListProduct" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:ObjectDataSource ID="odsProduct" runat="server" DeleteMethod="Delete" 
        InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" 
        SelectMethod="GetData" 
        TypeName="企业网站.DAL.DataSetProductTableAdapters.T_ProductsTableAdapter" 
        UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_Id" Type="Int64" />
        </DeleteParameters>
      
        
    </asp:ObjectDataSource>
    <asp:ObjectDataSource ID="odsCategory" runat="server" DeleteMethod="Delete" 
        InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" 
        SelectMethod="GetData" 
        TypeName="企业网站.DAL.DataSetProductTableAdapters.T_ProductsCategoryTableAdapter" 
        UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_Id" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="Name" Type="String" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="Original_Id" Type="Int32" />
        </UpdateParameters>
    </asp:ObjectDataSource>
    <a href="EditProduct.aspx?action=addnew">新增产品</a>
    <asp:ListView ID="lvProduct" runat="server" DataKeyNames="Id" 
        DataSourceID="odsProduct" oniteminserted="lvProduct_ItemInserted">
        
                
        
        <EmptyDataTemplate>
           
                        未返回数据。
           
        </EmptyDataTemplate>
        
        
        
        <ItemTemplate>
            <tr style="">
                <td>
                    <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="删除" onClientClick="return confirm('你确定要删除此记录吗?');" />
                     <a href='EditProduct.aspx?action=edit&id=<%# Eval("Id")%>'>编辑</a>
                </td>
                
                <td>

                    <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
                </td>
                <td>
                    <asp:DropDownList ID="DDL" runat="server" SelectedValue='<%#Eval("CategoryId") %>' DataTextField="Name" DataValueField="Id" DataSourceID="odsCategory" Enabled="false">
                    </asp:DropDownList>
                    
                </td>
              
                <td>

                    <asp:Label ID="PicPathLabel" runat="server" Text='<%# Eval("PicPath") %>' />
                </td>
            </tr>
        </ItemTemplate>
        <LayoutTemplate>
            <table runat="server">
                <tr runat="server">
                    <td runat="server">
                        <table ID="itemPlaceholderContainer" runat="server" border="0" style="">
                            <tr runat="server" style="">
                                <th runat="server">
                                </th>
                               
                                <th runat="server">
                                    名称</th>
                                <th runat="server">
                                    类别</th>
                               <th  runat="server">
                                    图片</th>
                            </tr>
                            <tr runat="server" ID="itemPlaceholder">
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr runat="server">
                    <td runat="server" style="">
                        <asp:DataPager ID="DataPager1" runat="server">
                            <Fields>
                                <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" 
                                    ShowLastPageButton="True" />
                            </Fields>
                        </asp:DataPager>
                    </td>
                </tr>
            </table>
        </LayoutTemplate>
        
        
        
    </asp:ListView>
</asp:Content>

    4).EditProduct.aspx(单个产品处理),在修改图片时我们用到了<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Bind("PicPath") %>' />,这个元素是在用户修改用户其它信息而不是图片时,用它来保存原来信息的值,把它做成参数提交给sql语句中的<asp:Parameter Name="PicPath" Type="String" />参数,否则更新后图片会丢失

     14.示例解析_第11张图片

<%@ Page Title="" Language="C#" MasterPageFile="~/master/SetFront.Master" AutoEventWireup="true" CodeBehind="EditProduct.aspx.cs" Inherits="企业网站.Admin.EditProduct" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:ObjectDataSource ID="odsProduct" runat="server" DeleteMethod="Delete" 
        InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" 
        SelectMethod="GetDataById" 
        TypeName="企业网站.DAL.DataSetProductTableAdapters.T_ProductsTableAdapter" 
        UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_Id" Type="Int64" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="CategoryId" Type="Int32" />
            <asp:Parameter Name="PicPath" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
        </InsertParameters>
        <SelectParameters>
            <asp:QueryStringParameter Name="Id" QueryStringField="Id" Type="Int64" />
        </SelectParameters>
        <UpdateParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="CategoryId" Type="Int32" />
            <asp:Parameter Name="PicPath" Type="String" />
            <asp:Parameter Name="Description" Type="String" />
            <asp:Parameter Name="Original_Id" Type="Int64" />
        </UpdateParameters>
    </asp:ObjectDataSource>
    <asp:ObjectDataSource ID="odsCategory" runat="server" DeleteMethod="Delete" 
        InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" 
        SelectMethod="GetData" 
        TypeName="企业网站.DAL.DataSetProductTableAdapters.T_ProductsCategoryTableAdapter" 
        UpdateMethod="Update">
        <DeleteParameters>
            <asp:Parameter Name="Original_Id" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="Name" Type="String" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="Original_Id" Type="Int32" />
        </UpdateParameters>
    </asp:ObjectDataSource>
    <asp:FormView ID="FormView1" runat="server" DataKeyNames="Id" 
        DataSourceID="odsProduct" oniteminserted="FormView1_ItemInserted" 
        onitemupdated="FormView1_ItemUpdated" 
        oniteminserting="FormView1_ItemInserting" 
        onitemupdating="FormView1_ItemUpdating" 
        onitemcommand="FormView1_ItemCommand">
        <EditItemTemplate>
            Id:
            <asp:Label ID="IdLabel1" runat="server" Text='<%# Eval("Id") %>' />
            <br />
            Name:
            <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
            <br />
            CategoryId:

            <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("CategoryId") %>' DataTextField="Name" DataValueField="Id" DataSourceID="odsCategory" />           
            <br />
            PicPath:
            <img id="Img1" src='<%#ResolveClientUrl("~/upload/images/"+Eval("PicPath")) %>' alt="没有图片" runat="Server" />
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Bind("PicPath") %>' />
            <br />
            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server"  TextMode="MultiLine" Columns="20" Rows="5"
                Text='<%# Bind("Description") %>' />
            <br />
            <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" 
                CommandName="Update" Text="更新" />
            &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" 
                CausesValidation="False" CommandName="Cancel" Text="取消" />
        </EditItemTemplate>
        <InsertItemTemplate>
            Name:
            <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
            <br />
            CategoryId:
            <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("CategoryId") %>' DataTextField="Name" DataValueField="Id" DataSourceID="odsCategory" />           
           
            <br />
            PicPath:
            <img id="img1" src='<%#ResolveClientUrl("~/upload/images/"+Eval("PicPath")) %>' alt="没有图片" runat="Server" />
            <asp:FileUpload ID="FileUpload1" runat="server" />
            
            <br />
            Description:
            <asp:TextBox ID="DescriptionTextBox" runat="server" TextMode="MultiLine" Columns="20" Rows="5"
                Text='<%# Bind("Description") %>' />
            <br />
            <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" 
                CommandName="Insert" Text="插入" />
            &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" 
                CausesValidation="False" CommandName="Cancel" Text="取消" />
        </InsertItemTemplate>
       
    </asp:FormView>
</asp:Content>

cs源码:

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

namespace 企业网站.Admin
{
    public partial class EditProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string action=Request["action"];
                if (action == "addnew")
                    FormView1.ChangeMode(FormViewMode.Insert);
                else if (action == "edit")
                    FormView1.ChangeMode(FormViewMode.Edit);
                else
                    throw new Exception("错误的action:" + action);
            }
           
        }

        protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            Response.Redirect("ListProduct.aspx");
        }

        protected void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            Response.Redirect("ListProduct.aspx");
        }

        protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            FileUpload fu = (FileUpload)FormView1.FindControl("FileUpload1");
            if (fu.HasFile)
            {
                string fileext = Path.GetExtension(fu.FileName);
                if ((fileext == ".jpg") || (fileext == ".jpeg") || (fileext == ".png") || (fileext == ".bmp"))
                {
                    fu.SaveAs(Server.MapPath("~/upload/images/"+ fu.FileName));
                   
                    e.Values["PicPath"] = fu.FileName;


                }
                else
                {
                    e.Cancel = true;
                    ClientScript.RegisterStartupScript(GetType(), "错误", "alert('文件格式不正确.');", true);
                }
            }
        }

        protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
        {
            FileUpload fu = (FileUpload)FormView1.FindControl("FileUpload1");
            if (fu.HasFile)
            {
                string fileext = Path.GetExtension(fu.FileName);
                if ((fileext == ".jpg") || (fileext == ".jpeg") || (fileext == ".png") || (fileext == ".bmp"))
                {
                    fu.SaveAs(Server.MapPath("~/upload/images/" + fu.FileName));
                   
                    e.NewValues["PicPath"] = fu.FileName;

                }
                else
                {
                    e.Cancel = true;
                    ClientScript.RegisterStartupScript(GetType(), "错误", "alert('文件格式不正确.');", true);
                }
            }
        }

        protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == "Cancel")
                Response.Redirect("ListProduct.aspx");
        }
    }
}

10.错误页面处理

   1).打开webconfig页面,设定当网站出错时,会自动 到错误页的设置,在customErrors 中mode有on,off,remoteonly三种,on表示在网站的服务器上也可以看到出错的页面,off表示关闭错误网页的显示,这样会显示网站的具体出错信息,一般用remoteonly就可以,让远端用户可以看到出错的页面,而在本地可以看到具体出错信息。defaultRedirect表示出错后默认转到的出错页,如果是网页找不到,则我们可以用statuscode来决定转到哪个业面。

  

<?xml version="1.0" encoding="utf-8"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细消息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <connectionStrings>
        <add name="DBConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DB.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
  
    <system.web>
      <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/ErrorPages/defaultErr.aspx">
        <error statusCode="404" redirect="~/ErrorPages/FileNotFound.htm" />
      </customErrors>
        <compilation debug="true" targetFramework="4.0" />
      <httpRuntime requestValidationMode="2.0"/>
    </system.web>

</configuration>

 出错默认页面,defaultErr.aspx的html

   

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="defaultErr.aspx.cs" Inherits="企业网站.ErrorPages.defaultErr" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    出错啦!
     
    </div>
    </form>
    <a href="/default.aspx">返回首页</a>
</body>
</html>

当调用出错的默认页面时,可以把出错的详细 信息写在具体的文件中,如本例中ErrorRecords.txt。如果要把出错信息写到文件中则需要更改webconfig中customErrors的redirectMode=ResponseRewrite才行.这样当错误面弹出时就会把详细信息写到文本中。

以下为cs:

 

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
              Exception ex=  HttpContext.Current.Server.GetLastError();
              File.AppendAllText(Server.MapPath("~/ErrorRecords.txt"), ex.StackTrace);
            }
        }

 

找不到文件的页面:

<!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>
    <title></title>
</head>
<body>
  对不起,你找的资源丢失了.
  <a href="/default.aspx">返回首页</a>
</body>
</html>

 

11.测试错误页,建立一错误页面ErrorTest.aspx,它的load事件中写入如下语句进行测试即可。

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SqlConnection conn = new SqlConnection("IP:127.0.0.1&db=tt");
                conn.Open();
            }
        }

12.其它和功能基本都一样,以下为运行截图

  14.示例解析_第12张图片14.示例解析_第13张图片14.示例解析_第14张图片14.示例解析_第15张图片

     

 

你可能感兴趣的:(解析)