i´m struggling a long time with this problem. I want the value of my selectListItem to use it in the controller to make the right API call.
Thats my Code in razor:
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Borussia Dortmund", Value = "10303", Selected= false},
new SelectListItem {Text = "FC Bayern München", Value = "10285", Selected= false},
new SelectListItem {Text = "Bayer 04 Leverkusen", Value = "10281", Selected= false},
.
.
.
}, "Value", "Text", 1);
@Html.DropDownList("ddlChosenTeam", selectList, "Team wählen", new { @class = "css-class" })
}
If i try the following in my Controller, it don´t know the selectList:
protected void SquadChosen_Click(object sender, EventArgs e)
{
int selectedSquad = selectList.SelectedValue;
}
I just want to pick the value like 10303 if "borussia Dortmund" is selected, please safe my time.
Edit: I wrote some other Code that is maybe more what i need. my Controller now:
public SelectList UserChosenSquad()
{
var ssl = new SelectList(new List<SelectListItem>
{
new SelectListItem {Text = "Borussia Dortmund", Value = "10303", Selected = false},
new SelectListItem {Text = "FC Bayern München", Value = "10285", Selected = false},
new SelectListItem {Text = "Bayer 04 Leverkusen", Value = "10281", Selected = false},
}, "Value", "Text");
return ssl;
}
The Model:
public class ChosenSquad
{
public string Text { get; set; }
public string Value { get; set; }
public bool Selected { get; set; }
}
now i struggle with the view
@model ChosenSquad
@{ @Html.DropDownListFor(model => model.Text, Model.SelectListItem, "Text", "-Team wählen-")
Is this the right way ? I need to show the DropDownList and then the value like before, i first want to see my list and then perhaps get the value with an if method that looks for selected item, right!?
Got it. I just edited my List like this:
public List<SelectListItem> ChosenSquad()
{
var ssl = new List<SelectListItem>
{
new SelectListItem {Text = "Borussia Dortmund", Value = "10303", Selected = false},
new SelectListItem {Text = "FC Bayern München", Value = "10285", Selected = false},
new SelectListItem {Text = "Bayer 04 Leverkusen", Value = "10281", Selected = false},
return ssl;
}
and in my view i got the following:
<select id=SquadSelectList asp-items="@((List<SelectListItem>)ViewData["Teams"])"></select>
now it renders the List and i just have to get the Value out of it when selected, help would be great but the most important thing is done.