简体   繁体   中英

DB filled DropDownList in EditorTemplate

I have an import page with a dynamic number of transactions. For each transactions, I have several plain text data labels and one DropDownList (Categories). I'm trying to populate this Category DropDownList with data from my ViewModel ( Categories ) by passing the Categories Model as additionalViewData to my EditorTemplate.

When I use the example below, I get the following error on the EditorTemplate page: Compiler Error Message: CS0411: The type arguments for method 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Any ideas on how to fix this?

ViewModel:

public class ImportViewModel
{
    public List<AbnAmroTransaction> AbnAmroTransactions { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
}

Model:

public class AbnAmroTransaction
{
    public string Currency { get; set; }
    public int DateTime { get; set; }
    public string Description { get; set; }
    public int CategoryId { get; set; }
}

Form:

@using (Html.BeginForm("ImportPreview", "Home", FormMethod.Post))
{
    <table>
    @Html.EditorFor(m => m.AbnAmroTransactions, new { Categories = Model.Categories });
    </table>
    <input id="btnSave" type="submit" value="Save data" />
}

EditorTemplate:

<tr>
    <td style="width: 80px;">
        @Html.Raw(CurrencyHelper.GetHtmlCurrency(Model.Currency, Model.Amount))
    </td>
    <td>@Model.DateTime</td>
    <td>@Model.Description</td>
    <td>@Html.DropDownListFor(Model.CategoryId, ViewData["Categories"])</td>
</tr>

You could provide the categories as additionalViewData to the Editor, like

@Html.EditorFor(m => m.AbnAmroTransactions, {Categories = Model.Categories});

but be aware of the implication, that you have to do that everywhere where you use that editor.

It might be better to use Editor where you can pass the categories along with the Model expression

It is not too Strongly typed, but in your controller you can populate the list of categories and place it in the ViewBag. Then you can use it in every Transaction you could have, and it is stored in memory just once.

If you place the Categories collection in each Transaction in your list you can have it multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM