Asp.net从一个集合中单值绑定

时间:2011-10-11 23:15:55

标签: asp.net web-services

大家好,我有一个项目需要从集合中执行单值绑定。我正在尝试创建一个具有一定程度分离的asp.net Web表单网站,而无需转到mvc。在网站中,我有一个页面,可以从Web服务调用方法。此方法返回结果集合。该页面旨在以结构化布局与网格或表单视图显示数据。有人可以指出我正确的方向(链接或样本)如何对asp.net中的集合结果执行单值绑定。

更新

为了澄清,该方法将返回该集合中的集合我具有以下属性(FirstName LastName高度权重)。是否可以将集合绑定到页面中的某个部分,然后在该部分中显示某个属性?

<div id="section1" DataSource="peopleCollection">
  <%# LastName %><br/>
  <span>Height: <%# Height %></span><br/>
  <span>Weight: <%# Weight %></span>
</div>

我想使用Web表单和MVC的伪实现而不使用MVC框架

提前致谢

1 个答案:

答案 0 :(得分:0)

'peopleCollection'是否具有单个元素或多个元素,其中每个元素都具有需要数据绑定的属性?如果是,那么您应该能够使用数据绑定控件,例如ListView / Repeater。究竟是什么问题?

或者你的意思是'peopleCollection'实际上是一个字典(名称 - 值对的集合) - 所以你有三个键进入字典,即高度,怀特和姓氏?在这种情况下,您可以使用单个元素创建虚拟数组,并将其与repeater / list-view绑定。例如,

代码隐藏

中的

// Assuming propertyCollection supports IDictionary<string, string>
var dummyArray = new IDictionary<string, string>[] { propertyCollection };
myControl.DataSource = dummyArray;
...
protected string GetValue(IDataItemContainer container, string propertyName)
{
   var properties = container.DataItem as IDictionary<string, string>;
   return properties[propertyName];
}
标记中的

<asp:Repeater ID="myControl" runat="server">
 <asp:ItemTemplate>
   <div id="section1" DataSource="peopleCollection">
     <%# GetValue(Container, "LastName") %><br/>
     <span>Height: <%# GetValue(Container, "Height") %></span><br/>
     <span>Weight: <%# GetValue(Container, "Weight") %></span>
   </div>
 </asp:ItemTemplate>
</asp:Repeater>

修改: 对于单个元素(具有相应的属性),您仍然可以使用基于转发器的方法。您所要做的就是放置一个元素数组(或任何可枚举的集合)并与转发器(或类似的控件)绑定。

但实际上,您并不需要使用单个元素进行数据绑定。您也可以使用标记,例如

<div id="section1">
  <%= People.LastName %><br/>
  <span>Height: <%= People.Height %></span><br/>
  <span>Weight: <%= People.Weight %></span>
</div>

其中People是暴露单个元素的受保护/公共属性。