Creating dynamic posts with htmltextwriter and submitting to the database

248 views Asked by At

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

There are 1 answers

2
Oscar On

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