我试图从asp.net dropdownlist控件中获取一个选定的项目,该控件是从jquery ajax调用填充的。我能够遍历屏幕上的项目,看到页面源中附加的选项,但当我试图从c#后端代码中获取值时,我得到空白值。 这就是我所拥有的:
$('#<%=Button2.ClientID %>').click(function () {
var Dropdown2 = $('#<%=ddlListAgents.ClientID %>');
Dropdown2.empty();
$.ajax({
type: "POST",
url: "WebForm3.aspx/fetchData",
data: "{selectedAgent: '" + $('#<%=txtAgentNameText.ClientID %>').val() +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Dropdown2.append(new Option("--Select Agent --", 0));
$.each(response.d, function (index, item) {
Dropdown2.append(new Option(item.Name, item.ID));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
在通话结束后,一切都设置好,我可以浏览选项。但是当我点击一个按钮并尝试在此代码中获取所选值时(测试代码):
protected void btnSelectAgentAdd_ServerClick(object sender, EventArgs e)
{
foreach (ListItem item in ddlListAgents.Items)
{
if (item.Selected.Equals(true))
{
item.Value.ToString();
}
else
{
item.Value.ToString();
}
}
string one = ddlListAgents.SelectedValue;
}
在第一个循环之后,代码从for循环中退出,而ddlListAgents.SelectedValue等于空字符串。
这是我用来获取数据集的方法:
[WebMethod]
public static List<AgentName> fetchData(string selectedAgent)
{
Dictionary<string, string> list = new Dictionary<string, string>();
BL.Client client = new BL.Client();
var agents = new List<AgentName>();
if (selectedAgent != string.Empty)
{
list = client.GetAgentNamesForPopupSearch(selectedAgent);
}
foreach (KeyValuePair<string, string> val in list)
{
agents.Add(new AgentName { ID = Convert.ToInt32(val.Key), Name = val.Value });
}
return agents;
}
欢迎提出任何建议。 在此先感谢Laziale
编辑: 添加了页面加载事件:
if (!IsPostBack)
{
Dictionary<string, string> list = new Dictionary<string, string>();
BL.Client client = new BL.Client();
list = client.GetAgentNamesForPolicies2(Convert.ToInt32(4));
ddlAgentName.DataSource = list;
ddlAgentName.DataTextField = "Value";
ddlAgentName.DataValueField = "Key";
ddlAgentName.DataBind();
ddlAgentName.Items.Insert(0, new ListItem("-- Select Agent --", string.Empty));
}
答案 0 :(得分:-1)
string selectedValue = Request.Form[ddlLanguage.UniqueID];