Assuming your view is strongly typed to a view model like this
public class CreateProduct
{
public IEnumerable<SelectListItem> Categories { set; get; }
public int SelectedCategory { set; get; }
}
And in your GET action method, you are creating an object of this view model, setting the Categories property and sending to the view
public IActionResult Create()
{
var vm = new CreateProduct();
vm.Categories = new List<SelectListItem>
{
new SelectListItem {Text = "Books", Value = "1"},
new SelectListItem {Text = "Furniture", Value = "2"}
};
return View(vm);
}
and in your view
@model CreateProduct
<form asp-action="create" asp-controller="Home">
<select asp-for="SelectedCategory" asp-items="@Model.Categories">
<option>Select one</option>
</select>
<input type="submit"/>
</form>
This will render the below markup(included only relevant parts of form/fields)
<form action="/Home/create" method="post">
<select data-val="true" id="SelectedCategory" name="SelectedCategory">
<option>Select one</option>
<option value="1">Shyju</option>
<option value="2">Sean</option>
</select>
<input type="submit"/>
</form>
Getting the selected dropdown value in form submission
You can use the same view model as your HttpPost action method parameter
[HttpPost]
public ActionResult Create(CreateProduct model)
{
//check model.SelectedCategory value
/ /to do : return something
}
Set an option as the selected one
If you want to set an option as the selected option, you may simply set the SelectedCategory
property value.
public IActionResult Create()
{
var vm = new CreateProduct();
vm.Categories = new List<SelectListItem>
{
new SelectListItem {Text = "Books", Value = "1"},
new SelectListItem {Text = "Furniture", Value = "2"},
new SelectListItem {Text = "Music", Value = "3"}
};
vm.SelectedCategory = 2;
return View(vm);
}
Rendering a Multi select dropdown/ListBox
If you want to render a multi select dropdown, you can simply change your view model property which you use for asp-for
attribute in your view to an array type.
public class CreateProduct
{
public IEnumerable<SelectListItem> Categories { set; get; }
public int[] SelectedCategories { set; get; }
}
In the view
@model CreateProduct
<form asp-action="create" asp-controller="Home" >
<select asp-for="SelectedCategories" asp-items="@Model.Categories">
<option>Select one</option>
</select>
<input type="submit"/>
</form>
This will generate the SELECT element with multiple
attribute
<form action="/Home/create" method="post">
<select id="SelectedCategories" multiple="multiple" name="SelectedCategories">
<option>Select one</option>
<option value="1">Shyju</option>
<option value="2">Sean</option>
</select>
<input type="submit"/>
</form>