Jquery Json无法找到资源

时间:2013-06-15 15:54:10

标签: jquery asp.net-mvc json select

我正在尝试使用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>

JQUERY:

$(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.您正在寻找的资源(或其中一个   依赖项)可能已被删除,其名称已更改,或者是   暂时不可用。请查看以下网址并制作   确保它拼写正确。

     

请求的网址:/ Admin / GetTeams

1 个答案:

答案 0 :(得分: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.LeagueIdint,则必须在客户端使用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()) }
相关问题