我正在做一个电影评论网站。 ShowMovie.aspx?ID = 6
我无法从.aspx页面的网址获取Id
<table border="1" cellpadding="1" cellspacing="1" style="width: 500px;">
<tbody>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblType" runat="server" Text='<%# Eval("Comment") %>'></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID='SqlDataSource1' runat='server' ConnectionString='<%$ ConnectionStrings:con %>'
SelectCommand='SELECT [Comment] FROM [Comment] where [MovieId]=<%= Request.QueryString("Id") %>'>
</asp:SqlDataSource>
</tbody>
</table>
但是我可以在.aspx.cs页面中使用
获取Idprotected void Page_Load(object sender, EventArgs e) {
Id = Request.QueryString["Id"];
String types = "";
con = new Connect().Connection();
cmd = new SqlCommand("Select * from Movie where Id=" + Id, con);
dr = cmd.ExecuteReader();
dr.Read();
lblTitle.Text = dr["Title"].ToString();
lblDescription.Text = dr["Description"].ToString();
Picture.ImageUrl = dr["Picture"].ToString();
dr.Close();
}
这是错误 '&lt;'附近的语法不正确。 异常详细信息:System.Data.SqlClient.SqlException:'&lt;'附近的语法不正确。
堆栈跟踪: [SqlException(0x80131904):'&lt;'附近的语法不正确。]
答案 0 :(得分:1)
SelectCommand不支持表达式。无论如何,你应该使用id的参数来避免sql注入。一个好的解决方案是像这样定义你的SqlDataSource:
<asp:SqlDataSource ID='SqlDataSource1' runat='server'
ConnectionString='<%$ ConnectionStrings:con %>'
SelectCommand='SELECT [Comment] FROM [Comment] where [MovieId]=@Id'>
<SelectParameters>
<asp:Parameter Name="Id" Type="Int32" DefaultValue="0" />
</SelectParameters>
</asp:SqlDataSource>
然后在页面加载中:
SqlDataSource1.SelectParameters["Id"].DefaultValue = Request.QueryString["Id"]