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");
To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With