Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select TagHelper Using List from ViewBag

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");
like image 772
Reafidy Avatar asked Aug 04 '15 08:08

Reafidy


People also ask

How do I get ViewBag data on my controller?

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.


2 Answers

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!

like image 64
N. Taylor Mullen Avatar answered Oct 13 '22 08:10

N. Taylor Mullen


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

like image 43
Joe Audette Avatar answered Oct 13 '22 08:10

Joe Audette