'Bind Dropdownlist with TagHelpers
I am trying to create a dropdownlist and bind with viewbag using ASP.NET Core tag helpers.
I can bind the dropdownlist using:
@Html.DropDownList("Area_id",
new SelectList(ViewBag.Areas, "Value", "Text"),
"Select an Area")
But I have hard time to use ASP.NET Core tag helper on HTML "Select":
<select asp-for="" asp-items="" />
My code always has red line under asp-for="Area_id"
saying Area_id
is not accessible. I tried to use asp-for="Id"
and still doesn't work. The GetAreas()
function works fine. Please help!
Model classes:
public class DegreeViewModel
{
public int Degree_id { get; set; }
public int Area_id { get; set; }
public List<SelectListItem> Areas { get; set; }
}
public IActionResult Index()
{
var vm = new DegreeViewModel();
vm.Areas = GetAreas();
return View(vm);
}
Controller:
private MyContext _context;
[BindProperty(SupportsGet = true)]
public int Area_id { get; set; }
[BindProperty(SupportsGet = true)]
public int? Degree_id { get; set; }
public IActionResult Index()
{
var vm = new DegreeViewModel();
vm.Areas = GetAreas();
return View(vm);
}
public List<SelectListItem> GetAreas()
{
var Areas = (from a in _context.Degrees
select new SelectListItem { Text = a.Area_name, Value = a.Area_id.ToString() }).ToList();
Areas.Add(new SelectListItem("Select", "0"));
return Areas;
}
Index.cshtml
@model DegreeViewModel
<form asp-action="GetResult" asp-controller="Home" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<label class="control-label">Areas</label>
<select asp-for="Area_id" asp-items="@(new SelectList(Model.Areas,"Value","Text"))" />
<span asp-validation-for="Area_id" class="text-danger"></span>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
Solution 1:[1]
The model's type you passed to page is IEnumerable
, So you can't use asp-for="Area_id"
. You need to use @foreach(var item in model){}
and then asp-for="item.Area_id"
. Because your question is how Bind Dropdownlist with TagHelpers and don't provide the post method, So i will just show how to use TagHelpers to bind dropdownlist.
public IActionResult Index()
{
//If you want to use `<select>`, you need to use specific class `SelectListItem`
List<SelectListItem> test = new List<SelectListItem>();
foreach (var item in GetAreas())
{
test.Add(new SelectListItem { Text = item.Area_name, Value = item.Id.ToString() });
}
ViewBag.Areas = test;
return View();
}
page
<select asp-items="@ViewBag.Areas" name="xxx" Id="xxx"></select>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Xinran Shen |