使用查询字符串的LinkBut​​ton重定向

时间:2017-08-29 09:47:52

标签: c# asp.net

我尝试制作一些简单的代码来增加数据库中的数字,使用转发器onitemcommand发送id&命令名。

增加数据库中int的代码工作正常,但是当我尝试添加重定向到"文章页面"在那里你可以阅读整篇文章。

所以我的问题是如何重定向LinkButton&amp;在重定向中创建查询字符串,如下所示<a>内的linkbutton(HTML5)标记//如果我添加了<a>(HTML5)标记,它不会更新数据库中的int //如果我删除了<a>(HTML5)标记,它将更新数据库int,但不会使用查询字符串重定向。

        <asp:Repeater ID="Repeater_Frontpage" OnItemCommand="Repeater_Frontpage_ItemCommand" DataSourceID="SqlDataSource1" runat="server">
            <ItemTemplate>
                    <asp:LinkButton CommandName="Visit" CommandArgument='<%# Eval("news_id") %>' runat="server"><a href="Article.aspx?category_id=<%# Eval("fk_categories_id") %>&amp;news_id=<%# Eval("news_id") %>">Read More</a></asp:LinkButton>
            </ItemTemplate>
        </asp:Repeater>




protected void Repeater_Frontpage_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "Visit")
    {
        SqlConnection conn = new SqlConnection(Helpers.ConnectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;

        int userId = int.Parse(e.CommandArgument.ToString());
        cmd.CommandText = "UPDATE News SET news_visits = news_visits + 1 WHERE news_id =" + userId;

        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();
    }
}

1 个答案:

答案 0 :(得分:0)

您可以将ItemIndex设置为CommandArgument

CommandArgument='<%# Container.ItemIndex %>' 

然后你可以从Repeater DataSource获取行

protected void repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{

    if (e.CommandName == "Visit")
    {
        var rowIndex = (int)e.CommandArgument;
        //Here I am assuming that your data source is a DataTable
        var row = ((DataTable)repeater.DataSource).Rows[0];
        var newsID = row.Field<int>("newsID");
        var categoriesID = row.Field<int>("fk_categories_id");

        Response.Redirect($"Article.aspx?category_id={categoriesID}& amp;news_id={categoriesID}");
        Response.Write($"Do something with {e.CommandArgument}");
    }

}