Bruce Tate 在他的书《Bitter Java》里谈到了Server-side Java 中的 antipatterns ,其中一个叫做“Magic Servlet” 。在这个Servlet 里,混杂了model,view和controller的编码,搞得责任不清,维护或扩展起来很麻烦。

其实在ASP.NET世界里也一样,如果你在论坛上混长了,类似下面的编码随处可见,我们不妨叫它为 “ Magic Page”, .。问题是,这些红字的语句是否应该出现在这里?

(:我知道这是个样品程序而已,求全责备恐怕是有点荒唐,但类似的编码在论坛上的帖子里经常出现,到底是什么原因呢?是程序员技术不精还是模仿造成的?)

<font color="#ff0000">\<%@ Import Namespace="System.Data" %>
\<%@ Import Namespace="System.Data.SqlClient" %></font>

\<html>

\<head>

<font color="#ff0000">SqlConnection myConnection;
    public Hashtable StateIndex;</font>

protected void Page_Load(Object Src, EventArgs E)
    {
<font color="#ff0000"> myConnection = new SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes");</font>

if (!IsPostBack)
            BindGrid();

<font color="#ff0000">StateIndex = new Hashtable();
        StateIndex["CA"] = 0;
        StateIndex["IN"] = 1;
        StateIndex["KS"] = 2;
        StateIndex["MD"] = 3;
        StateIndex["MI"] = 4;
        StateIndex["OR"] = 5;
        StateIndex["TN"] = 6;
        StateIndex["UT"] = 7;
</font>    }

public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
    {
        MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
        BindGrid();
    }

public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
    {
        MyDataGrid.EditItemIndex = -1;
        BindGrid();
    }

public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
    {
        if (Page.IsValid)
        {
<font color="#ff0000">String updateCmd = "UPDATE Authors SET au_id = \@Id, au_lname = \@LName, au_fname = \@FName, phone = \@Phone, "
                + "address = \@Address, city = \@City, state = \@State, zip = \@Zip, contract = \@Contract where au_id = \@Id";</font>

<font color="#ff0000">            SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);</font>

<font color="#ff0000">            myCommand.Parameters.Add(new SqlParameter("@Id", SqlDbType.NVarChar, 11));
            myCommand.Parameters.Add(new SqlParameter("@LName", SqlDbType.NVarChar, 40));
            myCommand.Parameters.Add(new SqlParameter("@FName", SqlDbType.NVarChar, 20));
            myCommand.Parameters.Add(new SqlParameter("@Phone", SqlDbType.NChar, 12));
            myCommand.Parameters.Add(new SqlParameter("@Address", SqlDbType.NVarChar, 40));
            myCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar, 20));
            myCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NChar, 2));
            myCommand.Parameters.Add(new SqlParameter("@Zip", SqlDbType.NChar, 5));
            myCommand.Parameters.Add(new SqlParameter("@Contract", SqlDbType.NVarChar,1));</font>

<font color="#ff0000">            myCommand.Parameters["@Id"].Value = MyDataGrid.DataKeys[(int)E.Item.ItemIndex];</font>

<font color="#ff0000">            String[] cols = {"LName","FName","Phone","Address","City","Zip"};</font>

<font color="#ff0000">            for (int i=0; i            {
                String colvalue = ((TextBox)E.Item.FindControl("edit_" + cols[i])).Text;
                myCommand.Parameters["@" + cols[i]].Value = Server.HtmlEncode(colvalue);
            }</font>

<font color="#ff0000">            myCommand.Parameters["@State"].Value = ((DropDownList)E.Item.FindControl("edit_State")).SelectedItem.ToString();</font>

<font color="#ff0000">            if (((CheckBox)E.Item.FindControl("edit_Contract")).Checked = true)
                myCommand.Parameters["@Contract"].Value = "1";
            else
                myCommand.Parameters["@Contract"].Value = "0";</font>

<font color="#ff0000">            myCommand.Connection.Open();</font>

<font color="#ff0000">            try
            {
                myCommand.ExecuteNonQuery();
                Message.InnerHtml = "Record Updated
" + updateCmd;
                MyDataGrid.EditItemIndex = -1;
            }
            catch (SqlException e)
            {
                if (e.Number == 2627)
                    Message.InnerHtml = "ERROR: A record already exists with the same primary key";
                else
                    Message.InnerHtml = "ERROR: Could not update record, please ensure the fields are correctly filled out";
                Message.Style["color"] = "red";
            }</font>

<font color="#ff0000">            myCommand.Connection.Close();</font>

BindGrid();
        }
        else
        {
            Message.InnerHtml = "ERROR: Please check each field for error conditions.";
            Message.Style["color"] = "red";
        }
    }

private void MyDataGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.EditItem)
        {
            for (int i = 0; i             {
                try
                {
                    if (e.Item.Controls[i].Controls[1].GetType().ToString() == "System.Web.UI.WebControls.TextBox")
                    {
                        TextBox tb = (TextBox)e.Item.Controls[i].Controls[1];
                        tb.Text = Server.HtmlDecode(tb.Text);
                    }
                }
                catch
                {

}
            }
        }
    }

public void BindGrid()
    {
<font color="#ff0000"> SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);</font>

<font color="#ff0000">        DataSet ds = new DataSet();
        myCommand.Fill(ds, "Authors");</font>

<font color="#ff0000">        MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
        MyDataGrid.DataBind();
</font>    }

\</head>

\<body style="font: 10pt verdana">

\<form runat="server">

\<h3>\<font face="Verdana">Updating a Row of Data w/ Validation\</font>\</h3>

\<span id="Message" EnableViewState="false" style="font: arial 11pt;" runat="server"/>\<p>

\<ASP:DataGrid id="MyDataGrid" runat="server"
      Width="800"
      BackColor="#ccccff"
      BorderColor="black"
      ShowFooter="false"
      CellPadding=3
      CellSpacing="0"
      Font-Name="Verdana"
      Font-Size="8pt"
      HeaderStyle-BackColor="#aaaadd"
      OnEditCommand="MyDataGrid_Edit"
      OnCancelCommand="MyDataGrid_Cancel"
      OnUpdateCommand="MyDataGrid_Update"
      DataKeyField="au_id"
      AutoGenerateColumns="false"
      OnItemDataBound="MyDataGrid_ItemDataBound"
    >

\<Columns>
        \<asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update"  ItemStyle-Wrap="false"/>
        \<asp:BoundColumn HeaderText="au_id" SortExpression="au_id" ReadOnly="True" DataField="au_id" ItemStyle-Wrap="false"/>
        \<asp:TemplateColumn HeaderText="au_lname" SortExpression="au_lname">
          \<ItemTemplate>
            \<asp:Label runat="server" Text='\<%# DataBinder.Eval(Container.DataItem, "au_lname") %>'/>
          \</ItemTemplate>
          \<EditItemTemplate>
            \<nobr>
            \<asp:TextBox runat="server" id="edit_LName" Text='\<%# DataBinder.Eval(Container.DataItem, "au_lname") %>'/>
            \<asp:RequiredFieldValidator id="au_lnameReqVal"
                ControlToValidate="edit_LName"
                Display="Dynamic"
                Font-Name="Verdana" Font-Size="12"
                runat=server>
                     
            \</asp:RequiredFieldValidator>
          \</EditItemTemplate>
        \</asp:TemplateColumn>
        \<asp:TemplateColumn HeaderText="au_fname" SortExpression="au_fname">
          \<ItemTemplate>
            \<asp:Label runat="server" Text='\<%# DataBinder.Eval(Container.DataItem, "au_fname") %>'/>
          \</ItemTemplate>
          \<EditItemTemplate>
            \<nobr>
            \<asp:TextBox runat="server" id="edit_FName" Text='\<%# DataBinder.Eval(Container.DataItem, "au_fname") %>'/>
            \<asp:RequiredFieldValidator id="au_fnameReqVal"
                ControlToValidate="edit_FName"
                Display="Dynamic"
                Font-Name="Verdana" Font-Size="12"
                runat=server>
                     

            \</asp:RequiredFieldValidator>
          \</EditItemTemplate>
        \</asp:TemplateColumn>
        \<asp:TemplateColumn HeaderText="phone" SortExpression="phone">
          \<ItemTemplate>
            \<asp:Label runat="server" Text='\<%# DataBinder.Eval(Container.DataItem, "phone") %>'/>
          \</ItemTemplate>
          \<EditItemTemplate>
            \<nobr>
            \<asp:TextBox runat="server" id="edit_Phone" Text='\<%# DataBinder.Eval(Container.DataItem, "phone") %>'/>
            \<asp:RequiredFieldValidator id="phoneReqVal"
                ControlToValidate="edit_Phone"
                Display="Dynamic"
                Font-Name="Verdana" Font-Size="12"
                runat=server>
                     *
            \</asp:RequiredFieldValidator>
            \<asp:RegularExpressionValidator id="phoneRegexVal"
                ControlToValidate="edit_Phone"
                ValidationExpression="[0-9]{3} [0-9]{3}-[0-9]{4}"
                Display="Dynamic"
                Font-Name="Arial" Font-Size="11"
                runat=server>
                    * Phone must be in form: XXX XXX-XXXX \<br>
            \</asp:RegularExpressionValidator>
          \</EditItemTemplate>
        \</asp:TemplateColumn>
        \<asp:TemplateColumn HeaderText="address" SortExpression="address">
          \<ItemTemplate>
            \<asp:Label runat="server" Text='\<%# DataBinder.Eval(Container.DataItem, "address") %>'/>
          \</ItemTemplate>
          \<EditItemTemplate>
            \<asp:TextBox runat="server" id="edit_Address" Text='\<%# DataBinder.Eval(Container.DataItem, "address") %>'/>
          \</EditItemTemplate>
        \</asp:TemplateColumn>
        \<asp:TemplateColumn HeaderText="city" SortExpression="city">
          \<ItemTemplate>
            \<asp:Label runat="server" Text='\<%# DataBinder.Eval(Container.DataItem, "city") %>'/>
   &n
bsp;      \</ItemTemplate>
          \<EditItemTemplate>
            \<asp:TextBox runat="server" id="edit_City" Text='\<%# DataBinder.Eval(Container.DataItem, "city") %>'/>
          \</EditItemTemplate>
        \</asp:TemplateColumn>
        \<asp:TemplateColumn HeaderText="state" SortExpression="state">
          \<ItemTemplate>
            \<asp:Label runat="server" Text='\<%# DataBinder.Eval(Container.DataItem, "state") %>'/>
          \</ItemTemplate>
          \<EditItemTemplate>
            \<asp:DropDownList runat="server" SelectedIndex='<font color="#ff0000">\<%# StateIndex[(String)((DataRowView)Container.DataItem)["state"]] %></font>' id="edit_State">
                  \<asp:ListItem>CA\</asp:ListItem>
                  \<asp:ListItem>IN\</asp:ListItem>
                  \<asp:ListItem>KS\</asp:ListItem>
                  \<asp:ListItem>MD\</asp:ListItem>
                  \<asp:ListItem>MI\</asp:ListItem>
                  \<asp:ListItem>OR\</asp:ListItem>
                  \<asp:ListItem>TN\</asp:ListItem>
                  \<asp:ListItem>UT\</asp:ListItem>
            \</asp:DropDownList>
          \</EditItemTemplate>
        \</asp:TemplateColumn>
        \<asp:TemplateColumn HeaderText="zip" SortExpression="zip">
          \<ItemTemplate>
            \<asp:Label runat="server" Text='\<%# DataBinder.Eval(Container.DataItem, "zip") %>'/>
          \</ItemTemplate>
          \<EditItemTemplate>
            \<asp:TextBox runat="server" id="edit_Zip" Text='\<%# DataBinder.Eval(Container.DataItem, "zip") %>'/>
            \<asp:RegularExpressionValidator id="RegularExpressionValidator1"
                ASPClass="RegularExpressionValidator" ControlToValidate="edit_Zip"
                ValidationExpression="[0-9]{5}"
                Display="Dynamic"
                Font-Name="Arial" Font-Size="11"
                runat=server>
                    * Zip Code must be 5 numeric digits \<br>
            \</asp:RegularExpressionValidator>
          \</EditItemTemplate>
        \</asp:TemplateColumn>
        \<asp:TemplateColumn HeaderText="contract" SortExpression="contract">
          \<ItemTemplate>
            \<asp:Label runat="server" Text='\<%# DataBinder.Eval(Container.DataItem, "contract", "{0}") %>'/>
          \</ItemTemplate>
          \<EditItemTemplate>
            \<asp:CheckBox runat="server" id="edit_Contract" Checked='\<%# DataBinder.Eval(Container.DataItem, "contract") %>'/>
          \</EditItemTemplate>
        \</asp:TemplateColumn>
      \</Columns>

\</ASP:DataGrid>

\</form>

\</body>
\</html>

跟本帖子的主题不相关,在上面的例程中,还有一个不懂的地方是,每次更新一条数据,为什么需要对整个DataGrid做DataBind()?为什么不能对当前这个DataGridItem做重新DataBind()?(DataGridItem是支持DataBind()的,但无法改变当前这个DataGridItem的ItemType)。。。。。。我的看法是,选择是否对整个DataGrid重新做DataBind()应该是高层次的policy,应该由应用的需求或程序员来决定,而不应该通过控件来强制执行