我有一个下拉列表,我正在尝试使用数据库中的数据填充我的 dorpdown 列表,为此我使用 MVC,那么我如何在 Controller 中编写方法以及如何为此编写 jquery: 这就是我在我看来实现的;
@Html.DropDownListFor("")
这是我可以找到的jquery:
$(document).ready(function()
{
$('#id_trial').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
source: "/ClassName/MethodName",
dataType: "json",
success: function (data) {
$.each(data.aaData,function(i,data)
{
alert(data.value+":"+data.text);
var div_data="<option value="+data.value+">"+data.text+"</option>";
alert(div_data);
$(div_data).appendTo('#ch_user1');
});
}
});
});
});
我认为这可能是 Controller 中的一种方法:
public virtual JsonResult MethodName()
{
IList<Fund> funds = _fundManager.Search();
var list = from x in funds
select new { Id = x.Code, Name = x.Name };
return Json(list);
}
我不知道如何链接所有这些并使其工作,非常感谢 ant 的帮助。
最佳答案
可以引用以下代码片段或以下链接上的详细文章
Dynamically populate the drop-down using jQuery in ASP.Net MVC3
在你的 Controller 中:
[HttpGet]
public virtual JsonResult LoadInfo()
{
var query = _repository.GetInformation(); //Here you return the data.
return Json(query, JsonRequestBehavior.AllowGet);
}
那么在你看来:
然后使用 jQuery 加载下拉列表
function LoadInfo() {
$.getJSON("@Url.Action(MVC.ControllerName.MethodName())", null,
function (data) {
$("#info").empty();
$.each(data, function () {
$("#info").append($("<option />").val(this.Id).text(this.Name));
});
});
}
关于jquery - 如何在mvc中填充下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23359132/