2012-12-08 29 views
0

我在做一個電影評論網站。 ShowMovie.aspxα-ID =在.aspx中獲取ID

我上無法從URL獲得標識在.aspx頁面中

<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頁面獲取標識

protected 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(); 

}

這是錯誤 「<」附近的語法不正確。 異常詳細信息:System.Data.SqlClient.SqlException:「<」附近的語法錯誤。

堆棧跟蹤: [SQLEXCEPTION(0x80131904):附近有語法錯誤<「。]

+0

在那裏你定義的ID? – Adil

+0

你有試過嗎? (硬括號) <%= Server.HTMLEncode(的Request.QueryString [ 「ID」])%> 參考: http://stackoverflow.com/questions/9725385/getting-a- url-parameter-into-asp-net-label –

+0

它位於ShowMovie.aspx頁面。 Id來自Default.aspx "> tayfun

回答

1

SelectCommand不支持表達式。無論如何,你應該使用你的ID參數,以避免SQL注入。一個好的解決辦法是定義你的SqlDataSource是這樣的:

<asp:SqlDataSource ID='SqlDataSource1' runat='server' 
ConnectionString='<%$ ConnectionStrings:con %>' 
SelectCommand='SELECT [Comment] FROM [Comment] where [MovieId][email protected]'> 
    <SelectParameters> 
     <asp:Parameter Name="Id" Type="Int32" DefaultValue="0" /> 
     </SelectParameters> 
</asp:SqlDataSource> 

然後在頁面加載:

SqlDataSource1.SelectParameters["Id"].DefaultValue = Request.QueryString["Id"]