I want dynamical add HTML on my div. I do this with:
newsAllScroller.InnerHtml = newsAllScroller.InnerHtml + "<br><center><b>";
List<DAL.News> newsList = DAL.NewsHandler.GetAllNews();
foreach (DAL.News n in newsList)
{
newsAllScroller.In开发者_Go百科nerHtml = newsAllScroller.InnerHtml + "<br>" + n.Betreff + " - ("
+ "<asp:HyperLink ID=\"news"+n.NewsID+"\" runat=\"server\" NavigateUrl=\"~/News.aspx?id=" + n.NewsID + "\""
+ " CssClass=\"newsLink\">"
+ "..."
+ "</asp:HyperLink>"
+ ")";
}
newsAllScroller.InnerHtml = newsAllScroller.InnerHtml + "</center></b>";
The HyperLink is not working (you cannot click it).
When I copy the hyperlink from the browser-source-code into an aspx-page it works, so it seems the syntax is all correct - but it doasn't work via code, why?
You cannot add server side control to HTML and think of it to behave normally, you would have to modify your code to
newsAllScroller.InnerHtml = newsAllScroller.InnerHtml + "<br>" + n.Betreff + " - ("
+ "<a href ="/News.aspx?id=" + n.NewsID + "\""
+ " class=\"newsLink\">"
+ "... </a>"
+ ")";
Because the aspx page is parsed only once before the output is sent to the browser. You can't print/output something and expect it to be parsed once more.
You should use a Repeater
instead of appending text to InnerHtml
. Something like this:
<asp:Repeater ID="myRepeater" runat="server" OnItemDataBound="myRepeater_ItemDataBound">
<ItemTemplate>
<br/><asp:Literal ID="myText" runat="server"/> - (<asp:HyperLink ID="myLink" runat="server" CssClass="newsLink" Text="..."/>)
</ItemTemplate>
</asp:Repeater>
...and then in code-behind:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myRepeater.DataSource = DAL.NewsHandler.GetAllNews();
myRepeater.DataBind();
}
}
void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
var myText = e.Item.FindControl("myText") as Literal;
var myLink = e.Item.FindControl("myLink") as HyperLink;
var news = e.Item.DataItem as DAL.News;
if (myText != null && myLink != null && news != null)
{
myText.Text = news.Betreff;
myLink.NavigateUrl = "~/News.aspx?id=" + news.NewsID;
}
}
}
I haven't tried the code myself but it should point you in the right direction. Check out the Repeater documentation for more information and examples.
精彩评论