0

我正在尝试在 MVC 中使用 jquery 填充下拉列表。这是我下面的代码。

控制器:

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

看法:

<% using (Html.BeginForm("GetTeams", "Admin"))
    {%>
    <%: Html.ValidationSummary(true)%>
    <table class="addStatLeague">
    <tr><td>Choose League: </td><td><%: Html.DropDownListFor(model => model.leagueId, Model.getLeagues, new { @class = "dropdownlistLeagueStyle" })%></td><td><input id="leagueButton" class="loginButton" value="GetTeams" type="submit" /></td></tr>
</table>

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

查询:

$(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>"));
     });
  });
  });
   })

出于某种原因,我收到了一个找不到资源的错误页面,如下所示。

无法找到该资源。

说明:HTTP 404。您要查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请查看以下 URL 并确保其拼写正确。

请求的 URL:/Admin/GetTeams

4

1 回答 1

2

尝试JsonRequestBehavior.AllowGet

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

要检查的另一件事是模型绑定:

$.getJSON("/Admin/GetTeams", { LeagueId: $(".dropdownlistLeagueStyle").val() }

应该:

$.getJSON("/Admin/GetTeams", { model: {LeagueId: $(".dropdownlistLeagueStyle").val() }}

如果StatisticModel.LeagueId在服务器端是int,你必须parseInt在客户端使用。

$.getJSON("/Admin/GetTeams", { model: {LeagueId: parseInt($(".dropdownlistLeagueStyle").val()) }}

更新:考虑使用更简单的解决方案:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTeams(int LeagueId)
{
    StatisticModel newModel = new StatisticModel(LeagueId);
    var teams = newModel.getTeams;
    return Json(teams,  JsonRequestBehavior.AllowGet);
}

客户端:

$.getJSON("/Admin/GetTeams", { LeagueId: parseInt($(".dropdownlistLeagueStyle").val()) }
于 2013-06-15T16:00:23.630 回答