简体   繁体   中英

Populating dropdown via AJAX Fails

I am looking to populate a dropdown via AJAX in my MVC project. In doing so, the "Network" debugging tools show a 404 when searching my url and always falls into the error function of my AJAX call.

My Javascript, which is housed at the bottom of my view, is as follows:

function PopulateTournamentDropdown() {
        $.ajax({
            url: '/Leaderboard/PopulateTournamentDropDownList',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                var ddlTournament = $("#ddlTournament");
                ddlTournament.empty();
                $.each(data, function (i, tournament) {
                    ddlTournament.append('<option value="' + tournament.Id + '">' + tournament.Name + '</option>');
                });
            },
            error: function () {
                alert('Failed to retrieve tournament.');
            }
        });
    }

    $(function () {

        $('#ddlTournament').change(PopulateTournamentDropdown);
        PopulateTournamentDropdown();
    });

My Controller is as follows:

public class LeaderboardController : Controller
    {
        public static string PopulateTournamentDropDownList()
        {
            var list = GetTournamentDetails();
            return JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented, JsonSetting);
        }
}

As of now, the method in the controller is never being hit.

Please Help.

I think the problem is with the Action being a static method. Can you try this:

public class LeaderboardController : Controller
{
    public ActionResult PopulateTournamentDropDownList()
    {
        var list = GetTournamentDetails();
        return Content(JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented, JsonSetting), "application/json");
    }
}

The controller action method should have the following signature:

public ActionResult PopulateTournamentDropDownList()
{
  ...
}

Note, that it is instance (not static) method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM