Jquery populate drop down list in mvc

16,771

This line is your problem:

$("#NameList").append(""+ foo.Name + "");

it needs to be:

$("#NameList").append(""+ foo.Text + "");

since the name of the team you are trying to display is under TEXT property in your JSON string...

I think you need to define what you're trying to do but I will explain to you 2 scenarios.

If you just have 1 drop down list on your page which is supposed to display to you the name of the soccer teams then you don't need to do this with AJAX. You can get the list of your teams in your controller action and then bind that list to your drop down list in the view. So lets say you have a domain model like this:

namespace ProjectName.Models
{
  public class Team
  {
     public int TeamId {get; set; }
     public string TeamName {get; set;}
  }
}

and you have a View model like this:

public class LeagueViewModel
{
   public int LeagueId {get; set; }
   public int SelectedTeamId {get; set;}
   public IEnumerable<ProjectName.Models.Team> Teams {get; set;}
}

then in your controller you have an action like this:

public ActionResult GetTeams()
{
    var model = new LeagueViewModel();
    var model.Teams = TeamsBusinessLogic.GetTeams();
    return ActionResult(model);
}

where TeamsBusinessLogic is an instance of your business logic class that fetches the list of teams from the database (you will have to write this on your own since I have no idea what type of data access layer are you using). Once you have this setup then in your view all you need is:

@model LeagueViewModel

this specifies the underlying type of your model (you need to reference full namespace of the view model here). Then all you need is:

<%: Html.DropDownListFor(model => model.SelectedTeamId, (SelectList)Model.Teams, new { @class = "dropdownlistStyle" })%>

Now the drop down list will populate with the list of teams that were fetched from your controller action.

The 2nd scenario is when you have 2 drop down lists and changing the value in one of them trigger the loading in another. This is what you see on the sites that sell cars when you 1st specify the manufacturer and then based on your selection the make and model drop down lists change. For this scenario you will need the ajax loader similar to what you have written. So again suppose we have a domain models like this:

namespace ProjectName.Models
{
  public class Team
  {
     public int TeamId { get; set; }
     public string LeagueId { get; set; }
     public string TeamName { get; set; }
  }

  public class League
  {
     public int LeagueId { get; set; }
     public string LeagueName { get; set; }
  }
}

You will also need a view model like this one:

public class LeagueViewModel
{
   public int SelectedLeagueId {get; set;}
   public IEnumerable<ProjectName.Models.League> LeaguesList {get; set;}
}

once you have those you need an action in your controller that populates available leagues into your LeagueViewModel:

public ActionResult Leagues()
{
    var model = new LeagueViewModel();
    var model.LeaguesList = LeagueBusinessLogic.GetLeagues();
    return ActionResult(model);
}

so now in your view you have the following at the top:

@model LeagueViewModel

and then

<%: Html.DropDownListFor(model => model.SelectedLeagueId, (SelectList)Model.LeaguesList, new { @class = "dropdownlistStyle" })%>

and somewhere in there you will have your empty drop down list that needs to be populated:

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

once you have that you can write your JQuery as following:

$(function() {
   $(".dropdownlistStyle").change(function () {
   $.getJSON("/Admin/GetTeams", { LeagueId: $(".dropdownlistStyle").val() },
      function(results) {
         $("#LeagueTeams").empty();
         $.each(results, function(i, team) {
            $("#LeagueTeams").append(""+ team.TeamName+ "");
         });
      });
  });

so basically your JQuery will envoke a method on the server called GetTeams in the controller called AdminController and pass it the ID of the selected League. The controller action will return a JSON list of teams. You then loop through this list of teams and append them to the select list.

All you need to write now is the actual controller action that gets you the teams:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetTeams(int LeagueId)
{
    var model = TeamsBusinessLogic.getTeams(LeagueId);
    return Json(model);
}

again you will need to write your own business logic that get you all the teams in specific league...

Share:
16,771
Mark Fenech
Author by

Mark Fenech

Updated on June 04, 2022

Comments

  • Mark Fenech
    Mark Fenech almost 2 years

    I am trying to populate a drop down list an I am still very confused about J query as I am very new to it.

    this is my code:

    in the controller:

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

    in view:

    <%: Html.DropDownListFor(model => model.teamIdHome, Model.getTeams, new { @class = "dropdownlistStyle" })%>
    

    the jquery:

    $(function() {
    $(".dropdownlistStyle").change(function () {
        $.getJSON("/Admin/GetTeams", { FooId: $(".dropdownlistStyle").val() },
           function(fooList) {
               $("#NameList").empty();
               $.each(fooList, function(i, foo) {
                   $("#NameList").append(""+ foo.Name + "");
               });
           });
       });
    

    });

    At the moment when clicking on the Get Teams button this is the result:

    [{"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"}]

    I am sure that my jquery is incorrect as I got that from a sample from a forum.

    Any help please?

  • Mark Fenech
    Mark Fenech almost 11 years
    thats not technically my problem. my problem is about FooList and NameList. I am not using those names and don't know what I should replace with
  • Marko
    Marko almost 11 years
    NameList in this case is the ID of your drop down list that you're trying to populate. FooList is the name you gave to your JSON that is coming back from the server.
  • Mark Fenech
    Mark Fenech almost 11 years
    ok so whats FooId ? foo ? and the difference between #NameList and .dropdownlistStyle
  • Marko
    Marko almost 11 years
    Look at my updated response and see which scenario fits your needs so that I can better help you. Also please explain your scenario in more details, what are you exactly trying to do edit or define a soccer league??? Please explain more...
  • Mark Fenech
    Mark Fenech almost 11 years
    Basically I have a drop down list with a list of soccer league. when a soccer league is chosen and a button to get teams is clicked. 2 drop down lists will be populated with the teams from that leagues. ok ?