这里需要帮助
这是我的模特
public class SelectOption
{
public String Value { get; set; }
public String Text { get; set; }
}
样本方法
public JsonResult GetJson()
{
var list = new List<SelectOption>
{
new SelectOption { Value = "1", Text = "Aron" },
new SelectOption { Value = "2", Text = "Bob" },
new SelectOption { Value = "3", Text = "Charlie" },
new SelectOption { Value = "4", Text = "David" }
};
return Json(list);
}
查看
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("/Json/GetJson", null, function(data) {
$("#MyList").addItems(data);
});
});
$.fn.addItems = function(data) {
return this.each(function() {
var list = this;
$.each(data, function(index, itemData) {
var option = new Option(itemData.Text, itemData.Value);
list.add(option);
});
});
};
$("#MyList").change(function() {
alert('you selected ' + $(this).val());
});
</script>
上面的代码没有任何错误,只是在加载所有内容时,Select / Dropdownlist将有4个空值,这意味着我可以点击DDL和那里的4个值,但是所有四肢都是空字符串。
任何人都知道为什么?
由于
答案 0 :(得分:2)
这是另一种实施方式:
@{ ViewBag.Title = "Index"; } <h2>Index</h2> <select id="MyList"> </select> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script> $(function () { LoadList(); }); function LoadList() { var procemessage = "<option value=''> Please wait...</option>"; $("#MyList").html(procemessage).show(); $.ajax( { url: "@Url.Action("GetJson", "Test")" , type: "GET", success: function (data) { var markup = "<option value=''>-Select Option-</option>"; for (var x = 0; x < data.length; x++) { markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>"; } $("#MyList").html(markup).show(); }, error: function (reponse) { alert("error : " + reponse); } }); } </script>
控制器:
使用System; 使用System.Collections.Generic; 使用System.Linq; 使用System.Web; 使用System.Web.Mvc;
namespace stackoverflow.Controllers
{
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetJson()
{
var list = new List<SelectOption>
{
new SelectOption { Value = "1", Text = "Aron" },
new SelectOption { Value = "2", Text = "Bob" },
new SelectOption { Value = "3", Text = "Charlie" },
new SelectOption { Value = "4", Text = "David" }
};
return Json(list, JsonRequestBehavior.AllowGet);
}
}
}
选择选项模型:
公共类SelectOption { public string Text {get;组; } public string Value {get;组; } }