【发布时间】:2020-07-26 20:52:45
【问题描述】:
我有带有用户电子邮件地址的下拉列表“ListBox”的网页。
当我在下拉列表中添加新的电子邮件用户时,如何创建一个更新下拉列表“ListBox”的功能?
我尝试了这个解决方案但没有成功,因为它清空了下拉列表,而不是添加新用户。
这是我的代码:
nnewuser.txuser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "prefix.aspx/Savepnusers" + qString,
data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if ($("[id*=txuser]").val()) {
alert("Ok");
alert(JSON.stringify(nnewuser));
$("[id*=ListBox1]").html(response);
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
return false;
});
保存用户
public class pnnusers
{
public string txuser { get; set; }
}
[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnusers(pnnusers nnewuser)
{
string sql = @String.Format(" INSERT INTO `tbl_email` (email) VALUES (?); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}
下拉列表
private void MTListBox1()
{
DataTable dt = new DataTable();
sql = @String.Format(" SELECT ");
sql += String.Format(" LOWER(Email) AS UserEmail ");
sql += String.Format(" FROM ");
sql += String.Format(" tbl_email ORDER BY LOWER(Email) ASC; ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
ListBox1.DataTextField = "UserEmail";
ListBox1.DataValueField = "UserEmail";
ListBox1.DataSource = dt;
ListBox1.DataBind();
}
}
catch (OdbcException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
command.Connection.Close();
}
}
}
}
【问题讨论】:
-
什么不完全有效?你有什么错误或什么吗?你也可以添加你的
Savepnusers方法吗? -
@SelimYıldız 好的,在第一个问题中添加了 Savepnusers
-
您的方法不返回任何内容,因此您不能在 ajax 中使用响应。你如何初始化你的
ListBox1?我建议你在调用 Savepnusers 方法后重新初始化你的下拉列表。 -
@SelimYıldız 怎么做?请问有什么例子吗?
-
我可以提供一个解决方案,但我需要看看你如何初始化你的下拉列表。你能补充一下吗?