【问题标题】:Exception "The name 'BindItem' does not exist in the current context"异常“当前上下文中不存在名称 'BindItem'”
【发布时间】:2018-10-10 07:53:31
【问题描述】:

我最近发现您可以在 GridView 或 DetailsView 等数据绑定控件的上下文中直接在 aspx 页面的标记中使用“BindItem”和“Item”(通过指定 ItemType 属性)。我现在想要实现的是成员的内联比较,例如:

    <asp:RadioButton Text="All Assigned" ID="rb1" 
         Checked='<%# BindItem.AllAssigned %>' 
         runat="server" GroupName="AllAssigned" />
    <asp:RadioButton Text="Responsible only"  ID="rb2" 
         Checked='<%# !BindItem.AllAssigned %>' 
         runat="server" GroupName="AllAssigned" />

在这种情况下,我需要双向绑定,因此我选择了 BindItem 表达式。 但似乎!BindItem.AllAssignedBindItem.AllAssigned == false 之类的表达式在标记中不起作用。他们给了我例外,比如

名称“BindItem”在当前上下文中不存在

DataBinding:DataContext.MyEntity 不包含名为“false”的属性。

这样的表达我要写什么?

【问题讨论】:

  • 也许你应该使用Eval,例如&lt;%# !(bool)Eval("BindItem.AllAssigned") %&gt;.
  • 在这种情况下我需要双向绑定。
  • 你想要像Bind()这样的双向绑定吗?我认为您不能将Bind() 与条件运算符一起使用,Bind() 只接受字段名称。您需要处理CheckedChanged 事件来检索否定值,或使用RadioButtonList 处理不同的单选按钮状态。
  • 我目前的方法是使用 Item 而不是 BindItem 并处理 LinqDataSource 的更新事件以确定哪个单选按钮被勾选。但这很不方便......

标签: asp.net data-binding strong-typing


【解决方案1】:

由于不能在数据绑定表达式中使用逻辑否定运算符,因此可以在数据绑定表达式中使用Eval()DataBinder.Eval() 来使用它,如下例所示:

<%-- alternative 1 --%>
<asp:RadioButton Text="Responsible only"  ID="rb2" 
         Checked='<%# !(bool)Eval("AllAssigned") %>' 
         runat="server" GroupName="AllAssigned" />

<%-- alternative 2 --%>
<asp:RadioButton Text="Responsible only"  ID="rb2" 
         Checked='<%# !Convert.ToBoolean(Eval("AllAssigned")) %>' 
         runat="server" GroupName="AllAssigned" />

如果您想启用双向绑定,而不是使用具有不同 ID 的单独单选按钮,请使用 RadioButtonList 并在 SelectedValue 属性中设置 Bind(),如下例所示:

<asp:RadioButtonList ID="rb" runat="server" SelectedValue='<%# Bind("AllAssigned") %>' RepeatDirection="Horizontal" ...>
    <asp:ListItem Text="All Assigned" Value="true"></asp:ListItem>
    <asp:ListItem Text="Responsible only" Value="false"></asp:ListItem>
</asp:RadioButtonList>

然后您可以使用rb.SelectedValue 检索选定的单选按钮值。

相关问题:Databinding of RadioButtonList using SelectedValue...possible?

【讨论】:

  • 是的,这对我有用。但我必须在 ListItems 中写 True 和 False(大写)
猜你喜欢
  • 2014-06-14
  • 1970-01-01
  • 2013-10-02
  • 2014-04-22
  • 2017-06-17
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多