Smaribaldurs
Smaribaldurs

Reputation: 3

MVC cascading dropdownlist filtered by a connecting database table

So I have a MVC on top of a SQL database and I'm creating a add to database form.

I have 4 tables that concern this:

So the thing is once a Club is selected by name I need to filter the Sports based on the ClubID. So If I select Club A I only want sports played at club A to show up.

Any ideas on how to accomplish this?

Upvotes: 0

Views: 898

Answers (1)

Groyoh
Groyoh

Reputation: 342

As I've told you in my comment you could use JQuery and its cascading dropdown plugin but if you still want to use vanilla JS you could do something like that:

HTML:

<select id="club" name="ClubId">
  <option selected="selected" value="?">Select a club</option>
  <option value="1">Club 1</option><!-- value is the ClubId -->
  <option value="2">Club 2</option>
  <option value="3">Club 3</option>
</select>
<select id="sport" name="SportId">
  <option value="?">Select a club first</option>
</select>

JS:

var clubSelect = document.getElementById("club");
var sportSelect = document.getElementById("sport");

var resetSportsOptions = function () {
    sportSelect.options.length = 1;
    if (clubSelect.value == "?") {
        sportSelect.options[0].text = "Select a club first ";
    } else {
        sportSelect.options[0].text = "Select a sport ";
    }
}

var addSportOption = function (sport) {
    var option = document.createElement("option");
    option.text = sport.Name;
    option.setAttribute("value", sport.SportId);
    sportSelect.add(option);
}

var sendAjaxRequest = function () {
    var r = new XMLHttpRequest();
    r.open("POST", "/Sports/InClub", true);
    r.onreadystatechange = function () {
        if (r.readyState != 4 || r.status != 200) 
            return;
        var sports = JSON.parse(r.responseText);
        for (var i = 0; i < sports.length; ++i) {
            addSportOption(sports[i]);
        }
    };
    r.send("clubId=" + sportSelect.value);
}

clubSelect.addEventListener("change", function () {
    resetSportsOptions();
    if (clubSelect.value != "?") {
      sendAjaxRequest();
    }
});

ASP.NET MVC:

public class SportsController : Controller{
  // Your usual code
  public ActionResult InClub(int clubId){
    var sports = from s in db.Sport
                 join sic in db.SportInClub on s.SportId = sic.SportId
                 where sic.ClubId == ClubId 
                 select s
    return Json(sports);
  }
}

Upvotes: 1

Related Questions