我有一個包含EditItemTemplate和InsertItemTemplate的ListView。這兩種形式幾乎分享了所有的標記。例如:ASP.NET ListView在EditItemTemplate和InsertItemTemplate中具有相同的標記
<asp:listview runat="server" ... >
<layouttemplate>...</layouttemplate>
<itemtemplate>
<p><%#Eval("Name")%></p>
<p><%#Eval("Title")%></p>
...
</itemtemplate>
<insertitemtemplate>
<p>Name: <asp:textbox runat=server text='<%#Bind("Name")%>' /></p>
<p>Title: <asp:textbox runat=server text='<%#Bind("Title")%>' /></p>
...
<asp:button runat=server commandname="Insert" text="Save" />
</insertitemtemplate>
<edititemtemplate>
<p>Name: <asp:textbox runat=server text='<%#Bind("Name")%>' /></p>
<p>Title: <asp:textbox runat=server text='<%#Bind("Title")%>' /></p>
...
<asp:button runat=server commandname="Update" text="Save" />
</edititemtemplate>
</asp:listview>
當然,在現實中有很多在插入和編輯模板回事(很多領域,具有格式化,驗證等),我討厭要保持相同的標記兩次。
我首先想到的是所有共享標記移動用戶控件(.ascx):
<insertitemtemplate>
<custom:myform runat=server />
<asp:button runat=server commandname="Insert" text="Save" />
</insertitemtemplate>
<edititemtemplate>
<custom:myform runat=server />
<asp:button runat=server commandname="Update" text="Save" />
</edititemtemplate>
不幸的是,雙向綁定(文=」 <%#綁定(‘富’) %>')僅在窗體位於用戶控件中時才起作用(它不會將控件中的數據持久保存到數據庫中)。
另一種方法是將所有共享標記移動到包含文件。服務器端包含是對傳統ASP的一種迴歸,但它們仍然可以在ASP.NET中使用,並且可以在這種情況下使用,因爲包含文件的內容被視爲與頁面上正確的標記一樣。
但是包含文件仍然有點混亂,並且有它們的缺點(例如VisualStudio對它們不太舒服)。有其他選擇嗎?
根據這篇文章:'http:// forums.asp.net/p/1344635/2729853.aspx',這是非常棘手的做它聲明。從代碼隱藏中創建模板會更容易。 – keyboardP 2010-02-02 14:43:12