-1

我对 jQuery 很陌生,是否有一些使用 jQuery 的代码可以用来在 MVC 中填充下拉列表?

我目前正在使用 MVC 模型来填充下拉列表。如何使用 jQuery 填充下拉列表以避免回发到服务器?

目前我正在使用json如下:

控制器:

   [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult GetTeams(StatisticModel model)
    {
        StatisticModel newModel = new StatisticModel(model.leagueId);
        var teams = newModel.getTeams;
        return Json(teams);
}

看法:

<%: Html.DropDownListFor(model => model.leagueId, Model.getLeagues, new { @class = "dropdownlistLeagueStyle" })%></td><td><input id="leagueButton" class="loginButton" value="GetTeams" type="submit" />

<select id="LeagueTeams"></select>

Javascript

$(function() {
$(".dropdownlistLeagueStyle").change(function () {
    $.getJSON("/Admin/GetTeams", { LeagueId: $(".dropdownlistLeagueStyle").val() },
  function (teams) {
      $("#LeagueTeams").empty();
      $.each(teams, function (i, team) {
         $("#LeagueTeams").append($("<option>" + team.Text + "</option>"));
     });
  });
  });
  })

但是,我在最后一个括号中收到“期望更多源字符”错误,并在测试时获取此数据:

[{"Selected":false,"Text":"Arsenal","Value":"1"},
{"Selected":false,"Text":"Aston Villa","Value":"3"},
{"Selected":false,"Text":"Cardiff City","Value":"20"},
{"Selected":false,"Text":"Chelsea","Value":"4"},
{"Selected":false,"Text":"Crystal Palace","Value":"22"}, 
{"Selected":false,"Text":"Everton","Value":"5"},
{"Selected":false,"Text":"Fulham","Value":"6"},
{"Selected":false,"Text":"Hull City","Value":"21"},
{"Selected":false,"Text":"Liverpool","Value":"7"},
{"Selected":false,"Text":"Manchester City","Value":"8"},
{"Selected":false,"Text":"Manchester United","Value":"9"},
{"Selected":false,"Text":"Newcastle United","Value":"10"},
{"Selected":false,"Text":"Norwich","Value":"11"},
{"Selected":false,"Text":"Southampton","Value":"13"},
{"Selected":false,"Text":"Stoke City","Value":"14"},
{"Selected":false,"Text":"Sunderland","Value":"15"},
{"Selected":false,"Text":"Swansea City","Value":"16"},
{"Selected":false,"Text":"Tottenham Hotspur","Value":"17"},
{"Selected":false,"Text":"West Bromwich Albion","Value":"18"},
{"Selected":false,"Text":"West Ham United","Value":"19"}]

不在下拉列表中

4

1 回答 1

1

您必须附加<option>到选择。不只是一个字符串。此外,您正在使用team.name. 在您的结果集中,每个对象都没有“名称”属性。然而有team.Text

$("#LeagueTeams").append($("<option>" + team.Text + "</option>"));

$(function() {
    $(".dropdownlistLeagueStyle").change(function() {
        $.getJSON("/Admin/GetTeams", {
            LeagueId: $(".dropdownlistLeagueStyle").val()
        }, function(results) {
            $("#LeagueTeams").empty();
            $.each(results, function(i, team) {
                // append an option with the team name in there
                $("#LeagueTeams").append($("<option>" + team.Text + "</option>"));
            });
        });
    });
});

我使用您获得的结果和选择制作了一个 jsFiddle。

jsFiddle

另一方面,您可能希望将控制器操作的返回类型更改为JsonResult而不是ActionResult.

于 2013-06-14T17:12:21.207 回答