Select TagHelper Using List from ViewBag

Reafidy picture Reafidy · Aug 4, 2015 · Viewed 9.4k times · Source

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");

Answer

N. Taylor Mullen picture N. Taylor Mullen · Aug 5, 2015

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!