Reputation: 3
I am trying to populate a drop down list with jquery in MVC. This is my code below.
Controller:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTeams(StatisticModel model)
{
StatisticModel newModel = new StatisticModel(model.leagueId);
var teams = newModel.getTeams;
return Json(teams);
}
View:
<% 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>"));
});
});
});
})
For some reason I am getting a resource not found error page as shown below.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Admin/GetTeams
Upvotes: 0
Views: 1442
Reputation: 48972
Try 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);
}
Another thing to check is model binding:
$.getJSON("/Admin/GetTeams", { LeagueId: $(".dropdownlistLeagueStyle").val() }
should be:
$.getJSON("/Admin/GetTeams", { model: {LeagueId: $(".dropdownlistLeagueStyle").val() }}
If StatisticModel.LeagueId
on server side is int
, you have to use parseInt
on client side.
$.getJSON("/Admin/GetTeams", { model: {LeagueId: parseInt($(".dropdownlistLeagueStyle").val()) }}
Update: consider using a simpler solution:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTeams(int LeagueId)
{
StatisticModel newModel = new StatisticModel(LeagueId);
var teams = newModel.getTeams;
return Json(teams, JsonRequestBehavior.AllowGet);
}
Client side:
$.getJSON("/Admin/GetTeams", { LeagueId: parseInt($(".dropdownlistLeagueStyle").val()) }
Upvotes: 2