使用Page.LoadTemplate和传递参数 [英] Use Page.LoadTemplate and Pass Parameters

查看:75
本文介绍了使用Page.LoadTemplate和传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据对象的类型将模板加载到ASP.NET ListView .但是,我需要在加载该参数之前将参数传递给该 ItemTemplate .加载到列表视图中的项目模板是 .ascx 用户控件.

I need to load a template to an ASP.NET ListView depending on the type of an object. However, I need to pass parameters to that ItemTemplate before loading it in. The item template that gets loaded into the list view is a .ascx user control.

ITemplate template = Page.LoadTemplate("~/Controls/Questions/TrueFalse.ascx");
listView.ItemTemplate = template;

我尝试将 template 强制转换为 UserControl TrueFalse (加载的用户控件的类型),但是两者都强制转换为空.

I've tried casting template as UserControl or as TrueFalse (the type of the user control that loads), but both cast to a null.

我需要传递一个带有信息的对象,以便控件显示.例如,在这种情况下,问题是对/错问题,因此模板将被传递给 Question 对象,该对象包含问题文本以及答案是对还是错.还会有其他问题类型,例如多项选择",简短答案"等.每个问题都需要使用不同的模板进行显示.如何将信息传递给 ListView 中的 ItemTemplate ?

I need to pass an object with information for the control to display. For example, in this case, the question is a True/False question, so the template will be passed a Question object that contains the question text plus whether the answer is true or false. There will be other question types, such as Multiple Choice, Short Answer, etc. Each of these needs to get displayed with a different template. How do I pass information to that ItemTemplate in the ListView?

我一直在使用此解决方案根据数据类型更改模板.我可以根据数据的类型显示不同的模板;我只是不知道如何在将数据传递给模板时将其作为列表视图项加载.

I've been using this solution to change templates according to the data's type. I can display different templates according to the data's type; I just don't know how to load the template as a list view item while passing data to it.

推荐答案

Through this blog post, I discovered that the secret is actually in retrieving the bound item, which in the case of a list view, is ListViewDataItem.

在用户控件中,此行代码将检索绑定到 ItemTemplate 的数据,并将其添加到页面(在我的情况下是 Question 我需要访问的对象):

This line of code, in the user control, will retrieve the data bound to the ItemTemplate and add it to the page (which, in my case, is the Question object I needed to access):

((Question)(DataBinder.GetDataItem((ListViewDataItem)Container))).WhateverProperty

当然,此前端代码被<%#...%> 标记包围.

This front-end code gets surrounded in <%# ... %> tags, of course.

这篇关于使用Page.LoadTemplate和传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆