0

I've created a page with dynamic posts that I'm getting from the database. Inside each post I need to have a button that when the user clicks on, it'll change a value in the database.

I've tried so many different things. Initially I started off rendering a button in HTML, but didn't know how to get it to interact with the database. I've seen AJAX submissions to databases, but don't know how I'd put it in my code.

I also looked at this Insert Link Button In String Builder but I couldn't get it to work. I've read that the onClick property won't work if I do it this way, so that brings me back to AJAX.

As these buttons are being generated dynamically, I'm not sure how how to do this. Even if someone can point me in the right direction, I'd really appreciate it.

Here's a simplified version of my code:

protected override void Render(HtmlTextWriter writer)
{
    using (SqlConnection conn = new SqlConnection(constring))
    {
        SqlDataAdapter ada = new SqlDataAdapter("SELECT postid, title, text, date FROM Posts", conn);
        conn.Open();
        DataTable dt = new dt();
        ada.Fill(table);

        //dynamic posts
        foreach (DataRow row in dt.Rows)
        {
            writer.AddAttribute("class", "col-sm-6 col-xs-6");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            //main post content
            writer.WriteLine(row["date"].ToString());
            writer.WriteLine("<h1>" + row["title"].ToString() + "</h1>");
            writer.WriteLine("<p>" + row["text"].ToString() + "</p>");
            //writer.Write("<button id='postbtn" + row["postid"].ToString()'">Read Post</button>");

            writer.RenderEndTag();
            writer.WriteLine();
        }
        conn.Close
    }
}
Community
  • 1
  • 1

1 Answers1

0

In order to post you need a valid form, so place your button inside a form tag with the right action set to point to your controller method.

First, render form tag with it action attribute, then render all necessary controls inside, then close form tag.

https://www.w3schools.com/html/html_forms.asp

Oscar
  • 13,594
  • 8
  • 47
  • 75
  • Would that be inside the foreach? That would generate a form for each button. Is there another way? – user7703048 Mar 13 '17 at 19:00
  • @user7703048 Usually you create a form for each element to be updated, so in your case it seems to me that it should go inside the foreach clause. It will allow you to have a postid field in every form so you could know what post should be updated. The data in the posted form will be sent to the server when the submit button is clicked. If you place all your elements in the same form, I don't know how you plan to get the id of the modified element. – Oscar Mar 14 '17 at 07:55