ASP.NET WebForm间传值异常:点击滚动新闻标题后WebForm3无内容展示
问题根因
- 最核心错误:WebForm2后端拼接新闻链接时,把a标签的
href属性错拼成了herf,导致点击后无法正确跳转传参,WebForm3拿不到新闻id自然没有内容输出 - 其他影响运行的问题:
- 数据库连接未主动释放,容易引发连接池溢出
- WebForm3直接拼接SQL语句,存在严重SQL注入风险
- 未校验参数x是否存在,空参时会触发SQL语法错误
- 部分HTML标签未正确闭合,会导致页面渲染异常
- 代码中数据库连接字符串的server、uid、pwd字段为空,需要填写你本地实际的数据库配置信息
修复后代码
WebForm2.aspx.cs
using System; using System.Data.SqlClient; namespace newsSite { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 这里替换为你实际的数据库连接字符串 string connStr = "server=你的数据库地址;uid=你的用户名;pwd=你的密码;database=news"; using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); SqlCommand cm = new SqlCommand("select id,title from articles", cn); using (SqlDataReader dr = cm.ExecuteReader()) { string strTitle = ""; while (dr.Read()) { // 修复herf拼写错误,属性加引号更规范 strTitle += $"<a href='WebForm3.aspx?x={dr["id"]}' target='_blank'>{dr["title"]}</a> "; } // 标签属性加引号,语法更规范 n.InnerHtml = $"<marquee id='news' onmouseover='news.stop()' onmouseout='news.start()'>{strTitle}</marquee>"; } } } } }
WebForm3.aspx.cs
using System; using System.Data.SqlClient; namespace newsSite { public partial class WebForm3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 先判断参数是否存在 if (Request.QueryString["x"] == null || string.IsNullOrWhiteSpace(Request.QueryString["x"].ToString())) { art.InnerHtml = "无效的新闻id"; return; } int newsId; // 校验id是否为数字 if (!int.TryParse(Request.QueryString["x"].ToString(), out newsId)) { art.InnerHtml = "新闻id格式错误"; return; } string connStr = "server=你的数据库地址;uid=你的用户名;pwd=你的密码;database=news"; using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); // 用参数化查询避免SQL注入 SqlCommand cm = new SqlCommand("select Title,Details,photo from articles where id=@id", cn); cm.Parameters.AddWithValue("@id", newsId); using (SqlDataReader dr = cm.ExecuteReader()) { if (dr.Read()) { // 修复标签闭合问题 art.InnerHtml += $"<b>{dr["Title"]}</b><br><br>"; art.InnerHtml += $"{dr["Details"]}<br>"; art.InnerHtml += $"<img src='images/{dr["photo"]}' alt='新闻配图' /><br>"; } else { art.InnerHtml = "该新闻不存在"; } } } } } }
内容的提问来源于stack exchange,提问作者user16588800
相关产品推荐
相关产品推荐

