我正在尝试基于数据库值创建动态li元素,输出类似于:
<li id="myUniqueLiID" runat="server"><a href="vaiable url from db">variable string from db</a></li>
li元素的数量将在运行时确定。我想和li元素一起使用,因为我觉得它在以后留下了最多的操作选项,因为它与我使用的几个asp项目相反,即asp:ListBox。
以下是我目前使用的代码
SqlDatabase myconnection= new SqlDatabase(@"myconnection string");
DbCommand myproc= myconnection.GetStoredProcCommand("sp_MySP");
using (IDataReader LoadAllItems = myconnection.ExecuteReader(myproc))
{
while (LoadAllItems.Read())
{
// retrieves ID from db
int myID = LoadAllItems.GetInt32(0);
// retrieves string from db
string myName = LoadAllItems.GetString(1);
// I have a static method that builds url based off id
// it takes an int and returns a string
string restURL = MyLibrary.MyClass.StaticURLMethod(myID);
//data bind to li element
myLiID.datasource = LoadAllItems;
//I think I build the li in datatextfield area but not
//sure if that is correct, or how to format.
myLiID.datatextfield = "";
myLiID.databind();
}
}
如果我走在正确的轨道上,请从这里向我们提供一些指导。如果我走向错误的方向,请向正确的道路寻求指导。
答案 0 :(得分:3)
以下是一些指导:
Repeater
将数据绑定到。确保在转发器中创建li元素。假设您创建了一个返回GetData
的方法Dictionary<int, string>
,然后您可以将该数据绑定到Repeater
。
Repeater
:
<asp:Repeater ID="rep" runat="server">
<ItemTemplate>
<li><a runat="server" id="myLink" /></li>
</ItemTemplate>
</asp:Repeater>
将数据绑定到Repeater,如下所示:
private void BindData(Dictionary<int, string> dict){
this.rep.ItemDataBound += new RepeaterItemEventHandler(rep_ItemDataBound);
this.rep.DataSource = dict;
this.rep.DataBind();
}
void rep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
KeyValuePair<int, string> kp = e.Item.DataItem as KeyValuePair<int, string>;
//... find the control and update it with the correct values
}
}
我会留给您实际找到控件并使用正确的文本和网址进行更新。
希望这在某种程度上有所帮助。
答案 1 :(得分:0)
以下是我从marapet获取建议后使用的确切代码:
<div class="filterlist">
<ul id="list">
<asp:Repeater ID="MyList" runat="server">
<ItemTemplate>
<li runat="server">
<asp:HyperLink ID="MyLink" runat="server" Text="" NavigateUrl=""/>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
这是
背后的代码 protected void Page_Load(object sender, EventArgs e)
{
//This method return a dictionary with a URL, and a name
if (!Page.IsPostBack)
this.BindDate((Dictionary<string, string>)MyLibrary.Data.DataHelper.GetMytList());
}
private void BindDate(Dictionary<string, string> dict)
{
this.RestList.ItemDataBound += new RepeaterItemEventHandler(e_ItemDataBound);
this.RestList.DataSource = dict;
this.RestList.DataBind();
}
void e_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
KeyValuePair<string, string> mydict = (KeyValuePair<string, string>)e.Item.DataItem;
HyperLink Link = (HyperLink)e.Item.FindControl("MyLink");
Link.NavigateUrl = mydict.Value.ToString();
Link.Text = mydict.Key.ToString();
}
}