下面是对上贴里的编码的初浅的重构,
- AuthorList.aspx:
<%@ Page Language=”C#” AutoEventWireup=”false” CodeBehind=”AuthorList.aspx.cs” Inherits=”JoyCode.AuthorListPage” %>
<html>
<head>
</head>
<body style=”font: 10pt verdana”>
<form id=”Form1″ 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”
>
<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 ID=”Label1″ 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 ID=”Label2″ 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 ID=”Label3″ 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 ID=”Label4″ 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 ID=”Label5″ runat=”server” Text='<%# DataBinder.Eval(Conta
iner.DataItem, “city”) %>’/>
</ItemTemplate>
&n
bsp; <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 ID=”Label6″ runat=”server” Text='<%# DataBinder.Eval(Container.DataItem, “state”) %>’/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat=”server” 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 ID=”Label7″ 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 ID=”Label8″ 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>
- AuthorList.aspx.cs:
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using JoyCode;
namespace JoyCode
{
public class AuthorListPage : System.Web.UI.Page
{
AuthorManager am;
protected HtmlGenericControl Message;
protected DataGrid MyDataGrid;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Load += new EventHandler(Page_Load);
this.MyDataGrid.EditCommand += new DataGridCommandEventHandler(MyDataGrid_Edit);
this.MyDataGrid.UpdateCommand += new DataGridCommandEventHandler(MyDataGrid_Update);
this.MyDataGrid.CancelCommand += new DataGridCommandEventHandler(MyDataGrid_Cancel);
this.MyDataGrid.ItemDataBound += new DataGridItemEventHandler(MyDataGrid_ItemDataBound);
this.MyDataGrid.AutoGenerateColumns = false;
this.MyDataGrid.DataKeyField = “au_id”;
am = new AuthorManager();
}
protected void Page_Load(Object Src, EventArgs E)
{
if (!IsPostBack)
BindGrid();
}
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)
{
string id = MyDataGrid.DataKeys[(int)E.Item.ItemIndex].ToString();
String[] cols = { “LName”, “FName”, “Phone”, “Address”, “City”, “Zip” };
String[] vals = new String[cols.Length];
for (int i = 0; i < cols.Length; i++)
{
String colvalue = ((TextBox)E.Item.FindControl(“edit_” + cols[i])).Text;
vals[i] = colvalue;
}
string lname = vals[0];
string fname = vals[1];
string phone = vals[2];
string address = vals[3];
string city = vals[4];
string zip = vals[5];
string state = ((DropDownList)E.Item.FindControl(“edit_State”)).SelectedItem.ToString();
bool contract = ((CheckBox)E.Item.FindControl(“edit_Contract”)).Checked;
try
{
am.UpdateAuthor(id, lname, fname, phone, address, city, state, zip, contract);
Message.InnerHtml = “<b>Record Updated</b><br>”;
MyDataGrid.EditItemIndex = -1;
}
catch (RecordExistException ex)
{
Message.InnerHtml = “ERROR: ” + ex.Message;
Message.Style[“color”] = “red”;
}
catch(UnknownException ex)
{
Message.InnerHtml = “ERROR: Could not update record, please ensure the fields are correctly filled out”;
Message.Style[“color”] = “red”;
}
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 < e.Item.Controls.Count; i++)
{
try
{
if (e.Item.Controls[i].Controls[1] is TextBox)
{
TextBox tb = (TextBox)e.Item.Controls[i].Controls[1];
tb.Text = Server.HtmlDecode(tb.Text);//这里是否算?
}
else if (e.Item.Controls[i].Controls[1] is DropDownList)
{
DropDownList ddl = e.Item.Controls[i].Controls[1] as DropDownList;
string state = (String)((DataRowView)e.Item.DataItem)[“state”];
ListItem li = ddl.Items.FindByText(state);
if (li != null)
{
ddl.SelectedIndex = ddl.Items.IndexOf(li);
}
}
}
catch
{
}
}
}
}
public void BindGrid()
{
MyDataGrid.DataSource = am.GetAuthors();
MyDataGrid.DataBind();
}
}
}
- Author.cs:
using System;
using System.Data;
using System.Web;
using System.Runtime.Serialization;
using System.Data.SqlClient;
namespace JoyCode
{
public class UnknownException : ApplicationException
{
public UnknownException() {}
public UnknownException(string message) : base(message) {}
protected UnknownException(SerializationInfo info, StreamingContext context) : base(info,context) {}
public UnknownException(string message, Exception innerException) : base(message, innerException) {}
}
public class RecordExistException : ApplicationException
{
public RecordExistException() { }
public RecordExistException(string message) : base(message) { }
protected RecordExistException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public RecordExistException(string message, Exception innerException) : base(message, innerException) { }
}
public class AuthorManager
{
SqlConnection myConnection;
public AuthorManager()
{
myConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings[“ConnectionString”]);
}
public DataView GetAuthors()
{
SqlDataAdapter myCommand = new SqlDataAdapter(“select * from Authors”, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, “Authors”);
return ds.Tables[“Authors”].DefaultView;
}
public void UpdateAuthor(string id, string lname, string fname, string phone, string address, string city, string
state, string zip, bool contract)
{
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”;
SqlCommand myCommand = new SqlCommand(updateCmd, myConnection);
myCommand.Parameters.Add(new SqlParameter(“@Id”, SqlDbType.NVarChar, 11)).Value = id;
myCommand.Parameters.Add(new SqlParameter(“@LName”, SqlDbType.NVarChar, 40)).Value =
HttpUtility.HtmlEncode(lname);
myCommand.Parameters.Add(new SqlParameter(“@FName”, SqlDbType.NVarChar, 20)).Value =
HttpUtility.HtmlEncode(fname);
myCommand.Parameters.Add(new SqlParameter(“@Phone”, SqlDbType.NChar, 12)).Value = HttpUtility.HtmlEncode(phone);
myCommand.Parameters.Add(new SqlParameter(“@Address”, SqlDbType.NVarChar, 40)).Value =
HttpUtility.HtmlEncode(address);
myCommand.Parameters.Add(new SqlParameter(“@City”, SqlDbType.NVarChar, 20)).Value = HttpUtility.HtmlEncode(city);
myCommand.Parameters.Add(new SqlParameter(“@State”, SqlDbType.NChar, 2)).Value = HttpUtility.HtmlEncode(state);
myCommand.Parameters.Add(new SqlParameter(“@Zip”, SqlDbType.NChar, 5)).Value = HttpUtility.HtmlEncode(zip);
myCommand.Parameters.Add(new SqlParameter(“@Contract”, SqlDbType.Int)).Value = contract;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
}
catch (SqlException e)
{
if (e.Number == 2627)
throw new RecordExistException(“A record already exists with the same primary key”);
else
throw new UnknownException();
}
finally
{
if (myCommand.Connection != null && myCommand.Connection.State == ConnectionState.Open)
myCommand.Connection.Close();
}
}
}
}
- web.config:
<configuration>
<appSettings>
<add key=”ConnectionString” value=”server=(local)\NetSDK;database=pubs;Trusted_Connection=yes”/>
</appSettings>
</configuration>
可以看出AuthorList.aspx.cs里纯粹是操作View里的对象以及Controller的编码,不再包含Model的编码。这些编码已经被移到另一个类,这个类完全可以属于一个新的类库项目。原先对SQL异常的处理,也改成了Model类抛出跟应用有关的异常。
当然,还有很多不满意之处,譬如AuthorList.aspx里的DataBinder.Eval里,还包含着数据库表的字段名(!),AuthorList.aspx.cs里对MyDataGrid里模板里的控件的处理也显得有些不干净。Author.cs类居然依赖System.Web (因为用了System.Web.HttpUtility类),SQL语句的处理也不满意,想象一下假如有很多这样的类的话,编码会有很多重复。依赖于web.config里的设置也不好,因为这样或多或少意味着这个类跟当前的aspx页的部署关系