我在自己的网站上也做过同样的事情。我就是这样做的:
首先,为控制器创建一个返回 JSON 值的操作:
public ActionResult GetCountryNames()
{
List<string> CountryNames = new List<string>();
CountryNames = context.GetCountries(); // your EF context to get countrynames from database
return Json(CountryNames.ToArray());
}
然后在你的视图中添加这个 html 标记:
<select id="countrylist" onchange="DoSomething();"></select>
这是您的下拉列表。它具有在“onchange”事件中声明的 javascript 函数,如果您想在值更改时执行某些操作。
最后,您需要添加您的 javascript 函数,该函数对您的控制器操作执行 ajax 调用,获取值并将其设置到您的下拉列表中:
function GetCountryList() {
var serviceURL = '/Home/GetCountryNames';
$.ajax({
type: "post",
dataType: "json",
url: serviceURL,
success: successFunc,
async: false,
error: errorFunc
});
function successFunc(data, status) {
var countrylist = $('#countrylist');
countrylist.empty();
for (var i = 0; i < data.length; i++) {
var $option = $("<option>", { id: "option" + i });
$option.append(data[i]);
countrylist.append($option);
}
}
function errorFunc(data, status) {
alert('error');
}
}
当您的文档准备好后,运行函数 GetCountryList()。
可能最简单的方法是使用 jQuery。像这样:
<script type="text/javascript">
$(document).ready(function () {
GetCountryList();
});
</script>