【问题标题】:DB filled DropDownList in EditorTemplate数据库在 EditorTemplate 中填充 DropDownList
【发布时间】:2012-05-20 16:59:21
【问题描述】:

我有一个包含动态交易数量的导入页面。对于每笔交易,我都有几个纯文本数据标签和一个 DropDownList(类别)。我正在尝试通过将类别模型作为附加视图数据传递给我的 EditorTemplate 来使用来自我的 ViewModel (Categories) 的数据填充此 CategoryDropDownList。

当我使用下面的示例时,我在 EditorTemplate 页面上收到以下错误: 编译器错误消息:CS0411:方法“System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)”的类型参数不能从用法推断。尝试明确指定类型参数。

关于如何解决这个问题的任何想法?

视图模型:

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

型号:

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

表格:

@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" />
}

编辑器模板:

<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>

【问题讨论】:

    标签: c# .net asp.net-mvc-3 drop-down-menu


    【解决方案1】:

    您可以将类别作为附加视图数据提供给编辑器,例如

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

    但请注意这意味着您必须在使用该编辑器的任何地方都这样做。

    使用编辑器可能会更好,您可以将类别与模型表达式一起传递

    【讨论】:

    • 感谢您的建议,试过了,还是有小问题。更新了我上面的问题:)
    • ViewData 中的对象不是强类型的,您必须对其进行强制转换,以便编译器可以推断出它的用途。
    • 嗨 Georg,我用这个来工作:@Html.DropDownListFor(m => m.CategoryId, new SelectList(ViewData["Categories"] as IEnumerable, " CategoryId", "Name")) 非常感谢!
    【解决方案2】:

    它的类型不是太强,但是在您的控制器中,您可以填充类别列表并将其放置在 ViewBag 中。然后你可以在你可能拥有的每个事务中使用它,并且它只存储在内存中一次。

    如果您将类别集合放在列表中的每个事务中,则可以多次使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      相关资源
      最近更新 更多