2012-01-16 93 views
0

我创建了一个从查询字符串加载数据的页面。然后按如下方式创建一个带有URL的链接。asp.net查询字符串数据绑定

http://localhost:61279/clubpage.aspx?CategoryID=1 

当我点击类别1时,我该如何拉取与查询字符串相关的数据。

我有一些代码,但它不工作。

</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    <h2> 
     Youth clubs</h2> 
    <p> 
     <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" 
     EnableViewState="False"> 
      <HeaderTemplate> 
       <ul> 
      </HeaderTemplate> 

      <ItemTemplate> 
       <%-- <%--<%-- You can use an anchor element... --%> 
      <%-- <li><a href='youthclubpage.aspx?CategoryID=<%# Eval("YouthClubID") %>'><%# Eval("youthclubname") %></a> - <%# Eval("description") %></li> --%>     

       <%-- Or a HyperLink Web control...---%> 
       <li><asp:HyperLink runat="server" Text='<%# Eval("youthclubname") %>' NavigateUrl='<%# "youthclubpage.aspx?CategoryID=" + Eval("YouthClubID") %>'></asp:HyperLink> 
        - <%# Eval("Description") %></li> 

      </ItemTemplate> 

      <FooterTemplate> 
       </ul> 
      </FooterTemplate> 
     </asp:Repeater> 
     <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:joanton7865org7272_youthpodcastConnectionString %>" 

     SelectCommand="SELECT [youthclubname], [description], [YouthClubID] FROM [youthclublist]"> 
    </asp:SqlDataSource> 
    </p> 

    </asp:Content> 
+8

精彩的网站! – 2012-01-16 12:25:09

+2

你如何绑定数据?通过代码后面?使用数据源控件? – robasta 2012-01-16 12:25:43

+0

这个问题太宽了。基本上你要求我们为你做所有事情。你应该试着告诉我们你有什么特别的问题。 – 2012-01-16 12:26:07

回答

1

您可以通过

int categoryId = 0; 

if(int.TryParse(Request.Params["CategoryID"]), out categoryId)) 
{ 
    // query data with categoryID 
} 
else 
{ 
    // no category id 
    Response.Redirect("Default.aspx"); 
} 

而且MSDN信息访问查询字符串上Request Params

0
int CatagoryID = Request["CatagoryID"]; 

string myQuery = "Select Fields from table where [Filtered column] = " + CatagoryID; 

这是你在找什么?

+1

SQL命令不应该像这样构建。 http://xkcd.com/327/ – Curt 2012-01-16 12:28:10

+0

它会导致“SQL注入”,所以更好的ti使用参数化查询 – 2012-01-16 12:41:00

+1

我通常使用存储过程的在线sql试图更好地理解问题你的例子更简洁: )。 – 2012-01-17 07:59:11

1

你可以使用这样的,并确保您使用参数化查询,以避免SQL注入 SqlCommand Class

int categoryId = 0; 

if(Request["CategoryID"]!=null) 
{ 
categoryID=Convert.ToInt32(Request["CategoryID"]); 
SqlConnection ConnObject = new SqlConnection("ConnString of your SQL Provider"); 
SqlCommand cmd = new SqlCommand("select some thing from your table where [email protected]",ConnObject); 
cmd.Parameters.AddWithValue("@catID", categoryId); 
SqlDatareadr dr= cmd.ExecuteReader(); 
while(dr.read()) 
{ 
// use the returned values from DB 
} 
} 
else 
{ 

//category not exist 
}