我在ASP.Net Web窗体中有一个奇怪的例子。我有一个中继器,我想循环一个列表并动态生成控件。我们如何在ASP.Net Repeater中访问循环变量和绑定变量?
如果我使用<%#
,
<% for (var index = 1; index < MyNamespace.Model.Count; index++)
{ %>
<div style="font-weight: bold"><%# Eval(String.Format("v{0}_vendor_name", index.ToString())) %>: </div>
<% } %>
我可以进入评估和演示,但不是我的循环变量。我得到下面的生成错误:
The name 'index' doesn't exist in the current context.
如果我使用<%=
,
<% for (var index = 1; index < MyNamespace.Model.Count; index++)
{ %>
<div style="font-weight: bold"><%= Eval(String.Format("v{0}_vendor_name", index.ToString())) %>: </div>
<% } %>
我没有得到任何编译错误,但是在运行时,我得到以下错误:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
我已经看过这个论坛上的一些问题,但他们都没有要求在一个语句中获取这两种类型的变量。
如果你想知道我在努力达到什么目的,我的DataTable
绑定到这个Repeater
有一些动态列。我想根据计数动态添加它们。所以,如果有2列,我的Eval应该选择v1_vendor_name,v2_vendor_name。
我有v1_vendor_name
,v2_vendor_name
在DataTable
绑定到这个Repeater
;而不是使用Eval("v1_vendor_name")
和Eval("v2_vendor_name")
,我试图使用循环,因此Eval
中的列是动态应用的。我必须动态执行此操作,因为我无法控制列的数量。它可能高达v10_vendor_name
。
我已经使用属性从后面的代码试图通过@tweray的建议,
for (this.index = 1; this.index < MyNamespace.Model.Count; this.index++)
{ %>
<div style="font-weight: bold"><%# Eval(String.Format("v{0}_vendor_name", this.index.ToString())) %>: </div>
<% } %>
但是,this.index
在EVAL始终以0即使我在循环分配1。
为什么不使用嵌套中继器?或者,如果你能够,切换到ASP.NET MVC的Razor视图引擎,这是更清洁和漂亮的外观。 – mason
@mason - 是的,它适用于MVC。但是,我必须插入对现有Web窗体应用程序的更改。你如何看待嵌入式中继器的工作原理? – techspider