简体   繁体   English

Asp.net UserControl-如何对列表中的对象进行数据绑定?

[英]Asp.net UserControl - How to Data-Bind objects from a list?

I am using asp.net 4.5 c#. 我正在使用asp.net 4.5 c#。 I have created a user control with the following member inside: 我创建了一个包含以下成员的用户控件:

  [Bindable(true)]
    public Product item
    {
        get{
            return _product;
        }
        set
        {
            _product = value;
        }

    }

I then use my control, while DataBinding a "Product" into the member above: 然后,我使用控件,同时将“产品”数据绑定到上述成员中:

  <script runat="server">
Product item=new Product();
            </script>  
                    <uc:productBox runat="server" item="<%#item%>"/>      

While this works, Trying to bind dynamic items from a list in the following way fails: 在这种情况下,尝试通过以下方式绑定列表中的动态项目失败:

  foreach (Product item in ProductList()){%>          
                    <uc:productBox runat="server" item="<%#item%>"/>       
            <%}%>

I get the following error: 我收到以下错误:

The name 'item' does not exist in the current context 名称“ item”在当前上下文中不存在

Why can't I bind items from a list and how can I solve this in order to work? 为什么我不能绑定列表中的项目,如何解决这个问题才能起作用?

Binding expressions can only access variables in the scope of the class or static members from anywhere visible, not the scope of any loop as the loop will be executed in the own scope in code behind, in real. 绑定表达式只能从可见的任何位置访问类范围内的变量或静态成员,而不能访问任何循环范围,因为该循环将在后面的代码中实际在其自身范围内执行。

You should rather use a Placeholder and populate it in code behind, or (even better) use the Repeater control that takes your ProductList and builds your productBox es. 您应该使用一个Placeholder并在后面的代码中填充它,或者(甚至更好) 使用Repeater控件来获取您的ProductList并构建productBox

So in the ItemTemplate of your Repeater you should put your ProductBox and use <%# (Product)Container.DataItem %> expression on your Item property like binding a simple list to a Repeater . 因此,在RepeaterItemTemplate ,应将ProductBox放在Item属性上并使用<%# (Product)Container.DataItem %>表达式,例如将简单列表绑定到Repeater

A small hint: Building foreach in the ASPX is not very well written. 一个小提示:在ASPX中构建foreach的代码不是很好。 Never do that. 绝对不要那样做。 Also the name convention insists to start with upper case letters on class / control / public member names. 此外,名称约定还坚持在类/控件/公共成员名上以大写字母开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM