简体   繁体   English

用htmltextwriter创建动态帖子并提交到数据库

[英]Creating dynamic posts with htmltextwriter and submitting to the database

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. 最初,我开始使用HTML渲染按钮,但不知道如何使它与数据库交互。 I've seen AJAX submissions to databases, but don't know how I'd put it in my code. 我已经看到AJAX向数据库提交的内容,但是不知道如何将其放入代码中。

I also looked at this Insert Link Button In String Builder but I couldn't get it to work. 我还查看了String Builder中的“插入链接”按钮,但无法正常工作。 I've read that the onClick property won't work if I do it this way, so that brings me back to AJAX. 我已经读到,如果以这种方式进行操作,onClick属性将不起作用,因此使我回到了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
    }
}

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. 首先,使用具有action属性的表单标签呈现,然后在内部呈现所有必需的控件,然后关闭表单标签。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM