【问题标题】:Trying to update select list options from a jQuery post results尝试从 jQuery 发布结果中更新选择列表选项
【发布时间】:2014-12-21 15:26:25
【问题描述】:

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

<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”。我得到了我的所有物品,但是从 Action Method 转移我的物品或者我在我的 javascript 中抓取它们的方式都不正确。谁能指出我的问题是什么?谢谢!

【问题讨论】:

    标签: javascript jquery .net json razor


    【解决方案1】:

    确实没有理由将 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。

    【讨论】:

    • 所以不是返回ActionResult,而是返回JsonResult?
    • 是的,它只需要一个普通的旧 JSON 而不是 SelectItem
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2013-11-15
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多