我希望从下拉列表中选择文本,其中数据通过jQuery绑定,并在c#函数中用于显示。
页面设计和jquery调用函数
<script src="../../JavaScript/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=ddlCountry]").change(function (e) {
$.ajax({
type: "POST",
url: "testing.aspx/getstateList",
data: '{value: "' + $(this).val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var ddlCustomers = $("[id*=ddlState]");
ddlCustomers.empty().append('<option selected="selected" value="">Select an State</option>');
$.each(r.d, function () {
ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
})
})
});
</script>
<form id="form1" runat="server">
<label for="validate-select">Country Name:</label>
<asp:DropDownList ID="ddlCountry" runat="server" >
<asp:ListItem Value="">Select an Country</asp:ListItem>
</asp:DropDownList>
<label for="validate-select">State Name:</label>
<asp:DropDownList ID="ddlState" runat="server">
<asp:ListItem Value="">Select an State</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnsave" runat="server" Text="Submit" OnClick="btnsave_Click" />
使用webmethod从数据库表中获取数据
[WebMethod]
public static List<ListItem> getstateList(string value)
{
SqlConnection strConnection = new SqlConnection("connection string");
strConnection.Open();
SqlCommand cmd = new SqlCommand("select state_name as 'output', id from stateMaster where country_id='101' and Status='ACTIVE' order by state_name", strConnection);
List<ListItem> customers = new List<ListItem>();
SqlDataReader sdr = cmd.ExecuteReader();//opr.getDataReaderTrans("select state_name as 'output', id from stateMaster where country_id='101' and Status='ACTIVE' order by state_name");
while (sdr.Read())
{
customers.Add(new ListItem
{
Value = sdr["id"].ToString(),
Text = sdr["output"].ToString()
});
}
return customers;
}
protected void btnsave_Click(object sender, EventArgs e)
{
string state = ddlState.SelectedItem.Text;
Response.Write(state);
}
答案 0 :(得分:0)
您可以使用dropdownlist.SelectedItem.Text
获取所选项目的文本,并使用dropdownlist.SelectedValue
获取所选项目的值。
检查以下样本:
protected void btnsave_Click(object sender, EventArgs e)
{
//Retrieve Selected Text from Dropdown
var countrySelText = ddlCountry.SelectedItem.Text;
//Retrieve Selected Value from Dropdown
var countrySelValue = ddlCountry.SelectedValue;
//Retrieve Selected Text from Dropdown
var stateSelText = ddlState.SelectedItem.Text;
//Retrieve Selected Value from Dropdown
var stateSelValue = ddlState.SelectedValue;
}
答案 1 :(得分:0)
获取您可以使用的选定文本:
var _Selected = document.getElementById("yourdropdownID");
var _SelectedIndex = _Selected.options[_Selected.selectedIndex].text;
或者如果你想获得价值:
var _Selected = document.getElementById("yourdropdownID");
var _SelectedIndex = _Selected.options[_Selected.selectedIndex].value;