I am new to web development and learning Dropdown HTML Helper. So, I have created the dropdown but I am not able to receive the selected value in the backend.
Below is my attempt.
View:
@model WebApplication3.Models.DropDownViewModel
<form method="post">
@Html.DropDownListFor(m => m.SongList, new SelectList(Model.SongList, "Value", "Text"), "Select menu", new { @class = "form-control" })
@* below is the use of each argument.*@
@*1. m=>m.SongList => It helps in strongly typing to the model*@
@*2. Model.SongList => It is the datasource for creating the dropdown*@
@*3. "Value" => This is the value behind each of the dropdown options*@
@*4. "Text" => This is the actual text*@
@*5. "Select Menu" => This is the first option that will appear in the dropdown*@
<input type="submit" value="Send" />
</form>
Model:
public class DropDownViewModel
{
public DropDownViewModel()
{
SongList = new List<SelectListItem>();
}
public int Id { get; set; }
public List<SelectListItem> SongList { get; set; }
}
Controller:
public ActionResult Index()
{
DropDownViewModel dropdown = new DropDownViewModel();
dropdown.SongList.Add(new SelectListItem { Text = "Four", Value = "4" });
dropdown.SongList.Add(new SelectListItem { Text = "Five", Value = "5" });
dropdown.SongList.Add(new SelectListItem { Text = "Six", Value = "6" });
dropdown.SongList.Add(new SelectListItem { Text = "Seven", Value = "7" });
return View(dropdown);
}
[HttpPost]
public ActionResult Index(DropDownViewModel viewModel)
{
******* viewModel.??? WHow to get the selected ID. Which variable will have that.*******
return View(dropdown);
}