我的 View 中有以下下拉菜单...
<div class="editor-field">
@Html.DropDownListFor(model => model.CategoryId, new SelectList(new List<string>(), ""), "Select ...")
</div>
我的 Controller 包含以下操作方法,我调用它来更新选项...
[HttpPost]
public ActionResult GetCategories(int ChallengeId, string Gender, DateTime BirthDate)
{
CategoriesContext db = new CategoriesContext();
ChallengesContext cc = new ChallengesContext();
Challenge challenge = cc.Challenges.Where(c => c.ChallengeId == ChallengeId).Single();
var categories = db.Categories.Where(c => c.GenderOption == Gender && c.SponsorId == challenge.SponsorId).AsEnumerable()
.Select(s => new SelectListItem { Text = s.CategoryName, Value = s.CategoryId.ToString() }).ToList();
SelectList list = new SelectList(categories);
return Json(list);
}
当页面上的另一个项目发生变化时,我调用以下函数:
function GetCategories() {
var _challengeid = $('#ChallengeId').val();
var _gender = $('#Gender').val();
var _birthdate = $('#Birthdate').val();
if (_birthdate != "" && _gender != "" && _challengeid > 0) {
$('html,body').css('cursor', 'wait');
var url = '@Url.Action("GetCategories", "Coach")';
$.post(url, { ChallengeId: _challengeid, Gender: _gender, BirthDate: _birthdate }, function (data) {
$("#CategoryId").empty();
$.each(data, function (index, val) {
$('#CategoryId')
.append($("<option></option>")
.attr("value", val.Text)
.text(val.Text));
});
$('html,body').css('cursor', 'auto');
}, "json");
}
下拉项只是充满了“System.Web.Mvc.SelectListItem”。我得到了我所有的元素,但是从操作方法转移我的元素或我在我的 javascript 中获取它们的方式都不对。谁能指出我的问题是什么?谢谢!
最佳答案
确实没有理由将 JSON 包裹在 SelectList
中。
var categories = db.Categories.Where(c => c.GenderOption == Gender && c.SponsorId == challenge.SponsorId)
.Select(s => new { Text = s.CategoryName, Value = s.CategoryId.ToString() });
return Json(categories);
检查浏览器中的调试器,data
响应应该是一个 JSON。
关于javascript - 尝试更新 jQuery 发布结果中的选择列表选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27590787/