【发布时间】:2013-02-02 17:39:33
【问题描述】:
注意:这是 .NET 4.5 中的 ASP.NET Web 窗体模型绑定,而不是 MVC。
我正在使用 ASP.NET Web 窗体 (4.5) 的新强类型模型绑定功能来生成可编辑的项目列表。这适用于查看初始列表、编辑项目和删除项目。但是,我在插入新项目时遇到了问题。
具体来说,在我的 EditItemTemplate 和 InsertItemTemplate 中,我有一个 DropDownList(嗯,实际上它是一个从 DropDownList 派生的自定义控件,但就这个问题而言,它是一个 DropDownList)。该控件在标记中定义如下...
<agp:ClientStatusDropDownList ID="ClientStatusID" runat="server"
SelectedValue="<%#: BindItem.ClientStatusID %>" />
在 EditItemTemplate 中,这很好,但是在 InsertItemTemplate 中,这会在运行页面时产生错误:Eval()、XPath() 和 Bind() 等数据绑定方法只能在一个数据绑定控件。
因此,我从 InsertItemTemplate 中删除了 SelectedValue="<%#: BindItem.ClientStatusID %>" 部分并再次尝试。这次没有错误消息,但是当调用ListView.InsertMethod 时,模型上的ClientStatusID 属性未设置为DropDownList 的值(而其余属性设置正确)。
ListView.InsertMethod:
public void ListView_InsertMethod(int ID) {
Model model = this.DbContext.Models.Create();
if (this.TryUpdateModel(model)) {
this.DbContext.SaveChanges();
this.ListView.DataBind();
}
}
模型类:
public class Model{
public Int32 ID { get; set; }
public String Description { get; set; }
public Boolean IsScheduleFollowUp { get; set; }
public Nullable<Int32> ClientStatusID { get; set; }
}
EditItemTemplate:
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="Description" runat="server" Text="<%#: BindItem.Description %>" />
</td>
<td>
<asp:CheckBox ID="IsScheduleFollowUp" runat="server" Checked="<%# BindItem.IsScheduleFollowUp %>" />
</td>
<td>
<agp:ClientStatusDropDownList ID="ClientStatusID" runat="server" SelectedValue="<%#: BindItem.ClientStatusID %>" />
</td>
<td>
<asp:Button ID="Update" runat="server" ClientIDMode="Static" CommandName="Update" Text="Update" />
<asp:Button ID="Cancel" runat="server" ClientIDMode="Static" CommandName="Cancel" Text="Cancel" />
</td>
</tr>
</EditItemTemplate>
InsertItemTemplate:
<InsertItemTemplate>
<tr>
<td>
<asp:TextBox ID="Description" runat="server" Text="<%#: BindItem.Description %>" />
</td>
<td>
<asp:CheckBox ID="IsScheduleFollowUp" runat="server" Checked="<%# BindItem.IsScheduleFollowUp %>" />
</td>
<td>
<agp:ClientStatusDropDownList ID="ClientStatusID" runat="server" />
</td>
<td>
<asp:Button ID="Insert" runat="server" ClientIDMode="Static" CommandName="Insert" Text="Add" />
</td>
</tr>
</InsertItemTemplate>
我原本以为是控件的 ID 用于确定模型上的属性值将被传递给(即 TextBox 被称为“描述”的地方,值将被传递给模型的“描述”属性)。显然情况并非如此,而是由“”控制,但是从这个问题的其余部分可以看出,我无法在“InsertItemTemplate”中使用这种语法。我不敢相信在这种情况下不支持 DropDownList,但是我找不到任何使用 Google 或 Bing 与 4.5 模型绑定一起使用 DropDownList 的示例(事实上,在 ASP 中新模型绑定的示例很少。 NET 4.5 使用除了几个 TextBox 控件之外的任何东西)。
谁能进一步说明这个问题(最好告诉我需要做什么)?
我看过的关于 SO 的其他问题...
- Binding a DropDownList in ListView InsertItemTemplate throwing an error
- ASP.NET ListView with identical markup in EditItemTemplate and InsertItemTemplate
- Bind SelectedValue of ASP.net DropDownList to custom object
- Databinding to ASP.NET DropDownList list in ListView
所有这些都使用旧样式的绑定方法,而不是 4.5 中的新方法
谢谢。
【问题讨论】:
-
仅供参考;我还尝试绑定到 ClientStatusID 不可为空的备用模型(这是代码隐藏,而不是标记)。没有区别,属性仍然没有设置。这(在我看来)排除了可以为空的属性中的任何潜在问题。
标签: webforms model-binding strong-typing asp.net-4.5