c# - 在 asp.net 中使用 ajax 调用更新下拉列表
问题描述
我有带有用户电子邮件地址的下拉列表“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
方法不返回任何内容,因此您不能在 AJAX 调用中使用响应。您需要的是在成功完成ListBox1
后重新初始化或附加新项目Savepnusers
:
其次,您似乎无法nnewuser
正确发送参数。您不需要pnnusers
类,只需使用string
类型作为参数。
所以服务器端:
public static void Savepnusers(string nnewuser)
在客户端,您需要使用 jquery 添加下拉列表项:
var txtUser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "prefix.aspx/Savepnusers",
data: JSON.stringify({ nnewuser: txtUser }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
//Since you can't use response object, you can append new item to dropdownlist
if (txtUser) {
$("[id*=ListBox1]").append('<option value="'+txtUser+'">'+txtUser+'</option>');
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
推荐阅读
- java - OptaPlanner 中无法解释的 NPE
- angular - 无法在角度 4 中隐藏错误消息
- c# - 使用适用于桌面应用程序 (WPF) 的 Azure AD 实施 SAML SSO
- python - 使用python从文本中提取具有不同格式的所有日期
- r - 如何使用 knn 在 r 中正确使用函数预测?
- javascript - jQuery找到给定类的第一个以下元素?
- rest - 使用 RESTful API 设计通过 FK 删除
- php - 如何从通过 PHP 创建的新图像中查找图像类型
- python-2.7 - 使用 python utf-8 编码显示特殊字符
- c# - 解决 NuGet 版本冲突