尝试从jQuery发布结果更新选择列表选项

时间:2014-12-21 15:26:26

标签: javascript jquery .net json razor

我的视图中有以下下拉列表...

<div class="editor-field">
  @Html.DropDownListFor(model => model.CategoryId, new SelectList(new List<string>(), ""), "Select ...")
</div>

我的控制器包含以下操作方法,我正在调用它来更新选项...

[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中抓取它们的方式都不对。任何人都可以指出我的问题是什么?谢谢!

1 个答案:

答案 0 :(得分:2)

你真的没有理由将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。