[英]My .Net form won't UPDATE to database successfully
我的網站上有一個簡單的/ adminarea /。 在此管理區域內,共有三個頁面:Default.aspx(新帖子),Edit.aspx和View.aspx。
默認允許我插入新記錄。 視圖允許我使用閱讀器在頁面上顯示數據庫文本,但“編輯”(由於某些未知原因)不想更新。
ASPX
<form id="form1" runat="server">
<DIV style="max-width: 1500px; margin: 0px auto;">
<table>
<tr>
<td>Enter selection text: </td>
<td>
<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="Button1" runat="server" Text="Submit" OnServerClick="Button1_Click1" />
<asp:HiddenField ID="postID" runat="server" />
</td>
</tr>
</table>
</DIV>
</form>
最初,我確實想知道是否在HTML中生成了postID,但是如果您查看源代碼,它確實會顯示postID。
我的C#
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data Source=db652255182.db.1and1.com; Initial Catalog=db652255182; User ID=dbo652255182; Password=290Plots$");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP 1 * From homepageSelection ORDER BY postID DESC");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
string messageInfo = "";
int postIDVal = 0;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
messageInfo += reader["selectionText"].ToString();
postIDVal = (int)reader["postID"];
}
con.Close();
TextBox1.Text = messageInfo;
postID.Value = postIDVal.ToString();
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("update homepageSelection set selectionText=@selectionText where postID=@postID", con);
cmd.Parameters.AddWithValue("@selectionText", TextBox1.Text);
cmd.Parameters.AddWithValue("@postID", postID.Value);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
}
}
我的表中只有一列:homepageSelection:selectionText
我沒有得到任何錯誤。
我也知道SQL注入(即使.Net對此有很多內置保護)。 出於學習目的,我相信這是可以的。
我(不是這個問題的重點)正在編寫一個腳本,該腳本在發送之前刪除了危險內容。
單擊某個按鈕時將觸發Page_Load事件,而在Button1_Click1事件之前將觸發它。 您應該將IsPostBack -statement添加到Page_Load事件中,並且僅在未回發頁面時才從數據庫加載數據。
這應該工作:
if (!IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP 1 * From homepageSelection ORDER BY postID DESC");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
string messageInfo = "";
int postIDVal = 0;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
messageInfo += reader["selectionText"].ToString();
postIDVal = (int)reader["postID"];
}
con.Close();
TextBox1.Text = messageInfo;
postID.Value = postIDVal.ToString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.