我正在尝试创建一个动态的新闻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打开,页面永远不会加载。我不知道是什么问题,因为我有一个控制台应用程序,可以获取消息,这是很好的工作。
任何帮助都很感激。谢谢!
发布于 2018-05-08 21:00:44
编辑
你对我的回答的评论有助于我更好地理解。我认为您的问题并不取决于您的代码,而是依赖于已知问题和Chrome+Visual Studio
简言之:
我测试了你的LoadNewsPage(),它确实很好。奇怪的是,您正在将HTML插入到Label文本中。
不要这样做,而是在标记中添加这个HTML:
<div id="MyNewsSection" runat="server"></div>然后替换这个
Label1.Text = resulHtml;使用
MyNewsSection.InnerHtml = resulHtml;另外,作为一个一般的调试帮助,在Chrome中按F12 :如果有任何错误,它们将显示给您。
https://stackoverflow.com/questions/50241687
复制相似问题