我遇到了使用数据库中的数据填充ASP DropDownList的问题,我正在尝试使用ajax和jquery,遵循教程但添加了我自己的数据。我遇到的问题是,当页面加载下拉列表为空时,代码在下面。
Html部分
<div id="mainitem1" class="mainItem" style="background-color: #000">
<div class="box" style="top: 20%; position: absolute; width: 60%; z-index: 1; height: 70%; background-color: #e8e8e8; left: 32%; font-weight: bold; font-size: 1.3vw;">
<div id="divdistSearch" style="position: relative; width: 100%; height: 100%; top: 0px; left: 0px;">
<table>
<tr>
<td></td>
<td>
<asp:DropDownList ID="ddlStates" runat="server"></asp:DropDownList>
</td>
</tr>
</table>
</div>
</div>
<img id="mainitem1-image" alt="" src="/powertap/images/Background1.jpg" style="position: absolute; top: 0px; left: 0px" />
<img id="mainitem1-image1" alt="" src="/powertap/images/taps-and-text.png" style="position: absolute; margin-left: auto; margin-right: auto; left: 0; right: 0;" />
</div>
</div>
这是Jquery Part,我在separaet .js文件中有这个,但我已经链接到它,在头部
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetStates",
data: '{}',
contenType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var ddlStates = $("[id*=ddlStates]");
ddlStates.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
ddlStates.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
这是VB中的代码部分,无法弄清楚我缺少的东西。
Imports System.Data
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
Public Class _Default103
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Session("isLoggedIn") Then
price_file.Visible = False
checkstock_icon.Visible = False
checkstock_title.Visible = False
End If
End Sub
<WebMethod()> _
Public Shared Function GetStates() As List(Of ListItem)
Dim query As String = "SELECT Id, State FROM States"
Dim constr As String = ConfigurationManager.ConnectionStrings("DistData").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query)
Dim states As New List(Of ListItem)()
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
states.Add(New ListItem() With {
.Value = sdr("Id").ToString(), _
.Text = sdr("State").ToString() _
})
End While
End Using
con.Close()
Return states
End Using
End Using
End Function
End Class
答案 0 :(得分:0)
我认为在您的示例中使用JSON背后没有任何价值。但无论如何,你首先没有绑定你的下拉列表。初始绑定可以添加到页面加载事件中。
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If !IsPostBack//Make sure this is only filled if the page is not posted back
GetStates();