<select> for <select> C # in javascript

I have ViewBag.List>, where I have competition, and each competition has a list of teams. Example: List {Premier League: [Arsenal, Chelsea et al.] Bundesliga: [Bayern Munich, Wolfsburg et al.]

I have 2 choices. When the user selects the first choice (competition), I want the second choice to have teams from the competition. If he chooses the Premier League, Arsenal, Chelsea, etc. will have a second choice.

I tried to select for each competition, and if he selects one, that one will be visible, and the others hidden or not, but all the selected ones are connected with the asp for the CurrentTeam line, and I can not put the command in the database.

Another option was with javascript function. Whenever the user selects a competition → onclick = "myfunction (this)" and in this 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 not use ViewBag in javascript function.

I just need a choice that responds to another choice and puts these 2 things into the database. Any suggestions? Thanks!

+5
source share
1 answer

In your view, you can create a JavaScript object that contains all the leagues and commands, and then read from this 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

+1
source

Source: https://habr.com/ru/post/1267318/


All Articles