1

我正在使用 Request.Form 来获取输入字段中的文本,但是该值始终为空。我正在尝试获取输入标签中的文本值并查询我的数据库。我正在使用将值写入输入标签的日期选择器。我曾尝试写入一个 asp 文本框,但问题是在使用 TextBox 中的文本查询数据库之后。当我选择一个新日期时,文本框不会使用 datepicker 中的新日期值进行更新。这就是我使用输入标签的原因。这里的问题是 Request.Form["input"] 总是得到一个空字符串。

.aspx 文件

<form runat="server" method="post">      
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Button ID="Button1" runat="server" Text="insert into db" OnClick="Button1_Click" />
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    </ContentTemplate>
</asp:UpdatePanel>
</form>

脚本.js

var picker = new Pikaday(
    {
        field: document.getElementById('input'),
        trigger: document.getElementById('scheduleDate'),
        minDate: new Date(Date.now()),
        disableDayFn: function (date) {
            // Disable Monday
            var allDates = date.getDate();
            return date.getDay() === 6 || date.getDay() === 0;
                //block out dates that are fully booked.
        },
        toString(date, format) { // using moment.js
            return moment(date).format('YYYY-MM-DD');
        },

    });

.cs 文件

protected void Button1_Click(object sender, EventArgs e)
    {
        string date = Request.Form["input"];
        
        using (SqlConnection connection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; Integrated Security = True"))
        {
            //string selectquery = "SELECT * FROM Events";
            string sqlquery = "INSERT INTO [Events] (start_date, end_date) VALUES ('" + date + "', '" + date + "')";
            connection.Open();
            SqlCommand command = new SqlCommand(sqlquery, connection);
            command.ExecuteNonQuery();
            connection.Close();

        }

    }
4

1 回答 1

1

您不需要(或不想)使用 request.form。

只需将控件拖放到页面中即可。然后它们可以在您的代码中自由使用。所以,说这个标记:

<ContentTemplate>
    <asp:Button ID="Button1" runat="server" Text="insert into db" OnClick="Button1_Click" />
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

</ContentTemplate>

现在,在你的代码中?

DateTime MyDate = DateTime.Parse(TextBox2.Text);

string MyTextBox1Text = TextBox1.Text;

因此,就您而言,您希望这样做:

using (SqlConnection conn = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; Integrated Security = True"))
{
    string sqlquery = "INSERT INTO [Events] (start_date, end_date) VALUES (@MyDate,@MyDate)";
    using (SqlCommand command = new SqlCommand(sqlquery, conn))
    {
        command.Parameters.Add("@MyDate", SqlDbType.Date).Value = TextBox1.Text;
        conn.Open();
        command.ExecuteNonQuery();
    }
}
于 2022-01-30T20:14:13.143 回答