从asp.net中的模板访问绑定的转发器项目
我已将项目列表设置为中继器的数据源,并创建了一个自定义模板。有没有办法直接访问模板中当前绑定的项目? 下面的示例代码
class MyObject
{
public string Somevalue{get;set;}
}
我的 Page_Load 模板中的
List<MyObject> selections = new List<MyObject>();
selections.Add(new MyObject());
Repeater1.ItemTemplate = new MyObjectTemplate();
Repeater1.DataSource = selections;
Repeater1.DataBind();
代码
public class MyObjectTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
//Get the current item
MyObject o = ????? as MyObject;
string txt = "<h1>"+ o.Somevalue + "</h1>";
LiteralControl h1 = new
LiteralControl(txt);
container.Controls.Add(h1);
}
}
我知道,如果我只想在转发器中显示“Somevalue”的值,会有更简单的方法来实现此目的,但显示哪些值以及如何显示的实际逻辑更加复杂。
I have set a list of items as datasource for a repeater and I have created a custom template. Is there any way to directly access the current bound item in the template ?
Example code below
class MyObject
{
public string Somevalue{get;set;}
}
Code in my Page_Load
List<MyObject> selections = new List<MyObject>();
selections.Add(new MyObject());
Repeater1.ItemTemplate = new MyObjectTemplate();
Repeater1.DataSource = selections;
Repeater1.DataBind();
The template
public class MyObjectTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
//Get the current item
MyObject o = ????? as MyObject;
string txt = "<h1>"+ o.Somevalue + "</h1>";
LiteralControl h1 = new
LiteralControl(txt);
container.Controls.Add(h1);
}
}
I know that If I just wanted to display the value of "Somevalue" in the repeater there would be easier ways of achieving this, but the actual logic of which values to display and how is more complicated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 DataItem容器。例如,
此方法的唯一问题是,如果您依赖回发时的视图状态来维护控件状态,则数据项将不是
MyObject
类型。在这种情况下,最好的诱饵是使用 DataBinder< /a> - 例如,You need to use DataItem from the container. For example,
Only issue with this approach is that if you are relying on the view-state on post-back to maintain the control state then the data item will not be of type
MyObject
. In such case, the best bait would be to use DataBinder - for example,