Reputation: 8451
I am currently trying to use taghelpers in asp.net 5. I want to use a select tag helper with a list from the ViewBag. Anything I put into the asp-for field gives me an error because it tries to pull it from the model which is IEnumerable instead of the view bag.
I want to replace this:
@model IEnumerable<InvoiceIT.Models.Invoice>
@using (Html.BeginForm())
{
<p>
@Html.DropDownList("Companies", String.Empty)
<input type="submit" value="Filter" class="btn btn-default" />
</p>
}
with this:
@model IEnumerable<InvoiceIT.Models.Invoice>
<form asp-controller="Invoice" asp-action="Index" method="post" class="form-horizontal" role="form">
<select asp-for="????" asp-items="ViewBag.Companies" class="form-control">
</select>
<input type="submit" value="Save" class="btn btn-default" />
</form>
Here is how I populate the select list in the controller:
ViewBag.Companies = new SelectList(await DbContext.Company.ToListAsync(), "CompanyID", "Name");
Upvotes: 8
Views: 13389
Reputation: 18301
If you don't want the asp-for
attribute to pull from the Model
directly you can override that behavior by providing an @
.
Aka:
<select asp-for="@ViewBag.XYZ">
...
</select>
Therefore, based on what you said I believe your bit becomes:
@model IEnumerable<InvoiceIT.Models.Invoice>
<form asp-controller="Invoice" asp-action="Index" method="post" class="form-horizontal" role="form">
@{
SelectList companies = ViewBag.Companies;
var currentlySelectedIndex = 0; // Currently selected index (usually will come from model)
}
<select asp-for="@currentlySelectedIndex" asp-items="companies" class="form-control">
</select>
<input type="submit" value="Save" class="btn btn-default" />
</form>
Hopefully this helps!
Upvotes: 11
Reputation: 36736
asp-for just needs to be the property with the current selected value and asp-items needs to be an
IEnumerable<SelectListItem>
this snippet is from working code in my project:
<select id="CompanyCountry" asp-for="CompanyCountry"
asp-items="Model.AvailableCountries" class="form-control"></select>
in my model I'm using
IList<SelectListItem>
for AvailableCountries
Upvotes: 3
Reputation: 1
you can try like this ...
@Html.DropDownListFor(model => model.Id_TourCategory, new SelectList(ViewBag.TourCate, "Value", "Text"))
public ActionResult TourPackage()
{
List<TourCategory> lst = new List<TourCategory>();
lst = db.TourCategories.ToList();
ViewBag.TourCate = new SelectList(lst, "Id", "CategoryName");
return View();
}
Upvotes: 0