[英]Get value from database ASP.NET web api in Boostrap Dropdown list using JavaScript
我正在嘗試從JSON中的數據庫Web API獲取數據,並使用jQuery在我的引導模式頁面中顯示它們。
這是我的html頁面
<div class="form-group">
<label for="Modell">Country</label>
<select class="form-control">
// those below I want to retrieve them from database, not like this hardcoded
<option value="1">USA</option>
<option value="2">Canada</option>
<option value="3">France</option>
</select>
</div>
而我的一半完成了jQuery:
function Countries()
{
$.ajax({
url: "/Api/Countries",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
// I don't know what to code here to get countries in select option
// And how to show them in my boostrap modal page
}
})
}
我的回復結構看起來像..
在我的國家/地區模型中,我有這個課程
public class CountriesModel
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}
在我的國家/地區實體中,我有以下代碼
public List<CountriesModel> GetCountries()
{
List<CountriesModel> lst = new List<CountriesModel>();
try
{
using (SqlConnection con = new SqlConnection(DBConnection.GetDBConnection()))
{
string sqlSelectString = "SELECT * FROM Countries";
command = new SqlCommand(sqlSelectString, con);
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
lst.Add(new CountryModel
{
CountryId = reader.GetInt32(reader.GetOrdinal("CountryId")),
CountryName = reader.GetString(reader.GetOrdinal("CountryName")),
});
}
return lst;
}
}
catch (Exception ex)
{
ErrorMessage = ex.Message;
}
return null;
}
然后在我的控制器中,我有這個控制器:
public List<CountriesModel> GetCountries()
{
return countryService.GetCountries();
}
當然,當我運行/ api / countries時,我會得到Json的回信,但是如何使用jQuery ... javascript ...來檢索它們的引導頁面呢?
為選擇的html分配一個ID
<select class="form-control" id="cntryDD">
</select>
然后在成功回調中,您可以綁定結果
for (var i = 0; i < result.length; i++) {
var val = result[i];
var text = result[i];
$('#cntryDD').addOption(val, text, false);
}
我不確定您的result
或響應結構是什么樣子,但是您可以對其進行調試並在值/文本字段中相應地填充屬性。
您可以看一下這篇文章 。
但是最短的方法是
$.each(result, function (key, value) {
$("#cntryDD").append($("<option></option>").val(value.CountryId).html(value.CountryName));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.