tags:

views:

295

answers:

3

Hi,

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.InnerHtml = 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?

+1  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.

Tor Valamo
Ok, how to solve?
Kovu
You need to call the HyperLink class from code, instead of asp markup.
Tor Valamo
+2  A: 

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>"
                    + ")";
Ravia
A: 

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.

Anders Fjeldstad