ASP.NET:在if语句中使用Eval

时间:2013-05-17 20:20:04

标签: c# asp.net if-statement eval repeater

我有一个转发器。过去,转发器中的每个项目都有一个相关的文本框。但是,现在我向重复项添加了一个属性,需要指定是否为该项使用了文本框,较大的文本框或复选框。

这是我的aspx代码:

<%if (Eval("DisplayType") == "LargeBox") { %>
    <asp:TextBox ID="largeBoxAnswer" Rows="8" runat="server" Width="200" MaxLength="2000" EvaluationQuestionID='<%# Eval("EvaluationQuestionId") %>' />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="largeBoxAnswer" Display="dynamic" Font-Bold="true" ErrorMessage="*" />
<%} %>
<%else if (Eval("DisplayType") == "CheckBox") { %>
    <asp:TextBox ID="checkBoxAnswer" runat="server" Width="200" MaxLength="100" EvaluationQuestionID='<%# Eval("EvaluationQuestionId") %>' />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="checkBoxAnswer" Display="dynamic" Font-Bold="true" ErrorMessage="*" />
<%} %>
<%else { %>
    <asp:TextBox ID="txtAnswer" runat="server" Width="200" MaxLength="100" EvaluationQuestionID='<%# Eval("EvaluationQuestionId") %>' />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtAnswer" Display="dynamic" Font-Bold="true" ErrorMessage="*" />
<%} %>

这不起作用,我收到以下错误: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

我发现了很多关于这个错误,但没有任何真正有助于解决这个特殊问题。

我是否正在以正确的方式做这样的事情?我对asp.net没有超级经验,所以我对这个问题采取不同的方法。如果这是最好的方法,我如何将逻辑移到后面的代码,这样才能正常工作?

1 个答案:

答案 0 :(得分:1)

错误告诉你你的if语句实际上并不在数据绑定上下文中,所以即使你的Eval确实有效,它向Eval推送的内容......“DisplayRule”...实际上并不存在于该行。< / p>

看一下这个链接; eval in if statement?

根据这些人的说法,你的答案可能在于ElementIfTrue或Visible属性。

所以你最终会得到这样的东西;

<asp:TextBox ID="largeBoxAnswer" ElementIfTrue='<%# Eval("DisplayRule") == "LargeBox" %>' Rows="8" runat="server" Width="200" MaxLength="2000" EvaluationQuestionID='<%# Eval("EvaluationQuestionId") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="largeBoxAnswer" Display="dynamic" Font-Bold="true" ErrorMessage="*" />
<asp:TextBox ID="checkBoxAnswer"  ElementIfTrue='<%# Eval("DisplayRule") == "CheckBox" %>' runat="server" Width="200" MaxLength="100" EvaluationQuestionID='<%# Eval("EvaluationQuestionId") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="checkBoxAnswer" Display="dynamic" Font-Bold="true" ErrorMessage="*" />
<asp:TextBox ID="txtAnswer"  ElementIfTrue='<%# Eval("DisplayRule") == "**notsure**" %>' runat="server" Width="200" MaxLength="100" EvaluationQuestionID='<%# Eval("EvaluationQuestionId") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtAnswer" Display="dynamic" Font-Bold="true" ErrorMessage="*" />

......我认为这不能解决你所有的问题,但它可能会帮助你解决问题。