#c# #asp.net
#c# #asp.net
Вопрос:
Я много ищу и публикую в этом вопросе, но не смог получить удовлетворительного ответа.Я хотел убедиться, что всякий раз, когда я делаю вызов серверу, значение текстового поля должно быть тем, которое является наиболее обновленным.
Но когда я делаю вызов серверу, старое значение текстового поля сохраняется.Я знаю, что это как-то связано с обратной отправкой, но я не получаю точного способа получить обновленное значение текстового поля в моем файле .cs.
Пожалуйста, скажите мне, какие необходимые шаги я должен предпринять, чтобы всегда получать последнее значение текстового поля.
Вот мой код, который не работает:
protected void Page_Load(object sender, EventArgs e)
{
int contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside not PostBack";
}
else
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text="Inside PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" contentID "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" TextBox1.Text "' where contentID= '" contentID "'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
msg_lbl.Text = "text" TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" ex;
}
finally
{
mycon.Close();
}
}
Вот мой код страницы aspx:
<asp:TextBox ID="TextBox1" runat="server" Height="500px"
TextMode="MultiLine" Width="90%" AutoPostBack="True"></asp:TextBox>
</p>
<p>
amp;nbsp;amp;nbsp;amp;nbsp;amp;nbsp;amp;nbsp;
<asp:Button ID="Button1" runat="server" Text="Delete post" />
amp;nbsp;
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Save changes" />
amp;nbsp;
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</p>
Пожалуйста, также скажите мне причину, по которой он не работает, и как я могу заставить его работать.
Спасибо,
Amandeep
Комментарии:
1. Можете ли вы опубликовать свою разметку aspx и некоторые примеры данных?
2. Пробовал устанавливать точки останова и отлаживать код?
3. Привет, Грег, я добавил код aspx, но в качестве примера данных, пожалуйста, скажите мне, чего вы ожидаете?
4. Button2_Click событие щелчка, как contentid передается туда .. это не общедоступная переменная! Сделайте это как общедоступную переменную или получите запрос querystring снова!
5. Спасибо anand за то, что отметил эту ошибку, поскольку я также объявил contentid как глобальную переменную, это не давало мне никакой ошибки, но была эта ошибка, которую я изменил. Но все же проблема не решена для текстового поля.
Ответ №1:
Согласно ASP.NET жизненный цикл Page_Load выполняется перед Button2_Click, поэтому вы должны показать свой обновленный текст в Button2_Click:
protected void Page_Load(object sender, EventArgs e)
{
contentID = Convert.ToInt32(Request.QueryString["contentid"]);
if (contentID != 0)
{
if (!this.IsPostBack)
{
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "Inside not PostBack";
}
}
else
Response.Write("Invalid URL for article");
}
public void getContentBody(int contentID)
{
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select content from content where contentID='" contentID "'";
//Response.Write(str);
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = str;
dr = command1.ExecuteReader();
if (dr.Read())
{
content = dr[0].ToString();
}
}
catch (Exception ex)
{
Response.Write("Exception reading data" ex);
}
finally
{
dr.Close();
mycon.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//string textboxvalue = Request.Form[TextBox1.UniqueID];
mycon.Open();
string query = "update content set content='" TextBox1.Text "' where contentID= '" contentID "'";
msg_lbl.Text = query;
try
{
MySqlCommand command1 = mycon.CreateCommand();
command1.CommandText = query;
command1.ExecuteNonQuery();
getContentBody(contentID);
TextBox1.Text = content;
msg_lbl.Text = "text" TextBox1.Text;
}
catch (Exception ex)
{
msg_lbl.Text = "Exception in saving data" ex;
}
finally
{
mycon.Close();
}
}