簡體   English   中英

動態HTML新聞頁面在C#中不起作用

[英]Dynamic html news page is not working in C#

我正在嘗試創建動態新聞html頁面。 當我嘗試動態創建html時出現問題。 我是C#的新手,也不知道出了什么問題。 這是我的C#代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NewsAPI;
using NewsAPI.Models;
using NewsAPI.Constants;

namespace NewsDemo
{
    public partial class Default1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                LoadNewsPage();
            }
        }

        protected void LoadNewsPage()
        {
            try
            {
                var newsApiClient = new NewsApiClient("key");
                List<string> mylist = new List<string>();
                mylist.Add("google-news");
                mylist.Add("bbc-news");
                mylist.Add("cnn");
                mylist.Add("the-new-york-times");
                var articlesResponse = newsApiClient.GetTopHeadlines(new TopHeadlinesRequest
                {
                    Sources = mylist,
                    Language = Languages.EN
                });
                if (articlesResponse.Status == Statuses.Ok)
                {             
                    string resulHtml = "";
                    resulHtml += "<table>";
                    foreach (var article in articlesResponse.Articles)
                    {
                        resulHtml += string.Format("<tr style='valign:top'>", "");
                        resulHtml += string.Format("<td width=20%><img src='{0}' width='250px' height='200px'></img></td>", article.UrlToImage);
                        resulHtml += string.Format("<td width=80%><a href='{0}'><h3>{1}</h3></a>{1}<br>{2}<br>{3}<br><br></td>", article.Url, article.Title, article.Author, article.Description);

                        resulHtml += string.Format("</tr>", "");
                    }

                    resulHtml += string.Format("</table>", "");
                    Label1.Text = resulHtml;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}

每當我嘗試運行它時(在VS中),Chrome都會打開,並且頁面永遠不會加載。 我不知道出什么問題了,因為我有一個控制台應用程序,可以獲取新聞並且運行正常。

任何幫助表示贊賞。 謝謝!

編輯

您對我的回答的評論有助於我進一步了解。 我認為您的問題不取決於您的代碼,而是取決於Chrome + Visual Studio的已知問題

簡而言之:

  1. 您可以使用其他瀏覽器進行調試
  2. 或者您禁用JavaScript調試

我測試了您的LoadNewsPage() ,它確實得到了HTML。 似乎奇怪的是,您正在將HTML插入Label的文本中。

而不是這樣做,請在您的標記中添加以下HTML:

<div id="MyNewsSection" runat="server"></div>

然后替換這個

Label1.Text = resulHtml;

MyNewsSection.InnerHtml = resulHtml;

另外,作為常規的調試幫助,在Chrome中按F12鍵:如果有任何錯誤,則會顯示給您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM