I have a ViewBag.List > where i have competition, and every competition has a list of teams. Example : List of {Premier League : [ Arsenal, Chelsea etc] Bundesliga : [ Bayern Munchen, Wolfsburg etc]
I have 2 selects. When the user selects the first select ( competition ), i want that the second select will have the teams from the competition. If he selects Premier League, the second select will have Arsenal,Chelsea etc.
I tried to have a select for every competition, and if he selects one, that one will be visible and the other ones hidden or none, but all the selects are linked with asp-for string CurrentTeam and i can't put the team in the database.
Another option was with a javascript function. Whenever the user selects a competition - > onclick = "myfunction (this)" and in that function i have something like this:
function myFunction(select) {
var sel = document.getElementById("teams");
if (select.value == 'Premier League') {
sel.innerHTML = "";
@foreach(var team in ViewBag.List[0]) // Premier League
{
@: var x = document.createElement("OPTION");
@: x.setAttribute("value", @team);
@:var t = document.createTextNode(@team);
@: x.appendChild(t)
@: sel.appendChild(x);
}
}
else // the other competitions
But i can't use ViewBag in javascript function.
I just want a select that reacts to another select and to put those 2 things in the database. Any suggestions ? Thanks!
In your View, you can build a JavaScript object which holds all leagues and teams, and then read from that object in your JavaScript code:
Controller:
[HttpGet]
public ActionResult Index()
{
ViewBag.List = new Dictionary<string, string[]>
{
{ "Premier League", new[] { "Arsenal", "Chelsea" } },
{ "Bundesliga", new[] { "Bayern Munchen", "Wolfsburg" } },
};
return View();
}
View:
...
<script type="text/javascript">
//Complete list of leagues and their teams:
var leagues = {
@foreach(var l in ViewBag.List)
{
@: '@l.Key': [
foreach(var team in ViewBag.List[l.Key])
{
@: '@team',
}
@: ],
}
};
...
Example:
https://dotnetfiddle.net/d0FrGr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With