Tayfun
Tayfun

Reputation: 698

get ID in .aspx page

I'm doing a movie review site. ShowMovie.aspx?Id=6

I cann't get Id from url in .aspx page

 <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>

but i can get Id in .aspx.cs page with

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

}

this is the error Incorrect syntax near '<'. Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '<'.

Stack Trace: [SqlException (0x80131904): Incorrect syntax near '<'.]

Upvotes: 0

Views: 2703

Answers (1)

Flavia Obreja
Flavia Obreja

Reputation: 1237

SelectCommand doesn't support expressions. Anyway, you should use parameter for your Id to avoid sql injection. A good solution would be to define your SqlDataSource like this:

  <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>

And then in page load:

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

Upvotes: 1

Related Questions