我遇到了无法调用正确的 DisplayTemplate 的问题。
我有两个模型:
CompanyName.Application.Web.Controllers.SharedViewModels.PaymentItemViewModel
CompanyName.Application.ViewModels.SharedViewModels.PaymentItemViewModel
这些对象在 IEnumerable 中使用,然后传递给 DisplayTemplate。
DisplayTemplates/PaymentItemViewModel.cshtml:
@model CompanyName.Application.ViewModels.Web.SharedViewModels.PaymentItemViewModel
DisplayTemplates/PaymentItems.cshtml:
@model CompanyName.Application.Web.Controllers.SharedViewModels.PaymentItemViewModel
如果我尝试像这样调用 PaymentItems.cshtml 的显示模板:
@Html.DisplayFor(model => model.PaymentItems, "DisplayTemplates/PaymentItem")
它在提示传递到字典中的模型与字典期望的模型类型不同时抛出错误。 model.PaymentItems 中的类型绝对是一个 IEnumerable
CompanyName.Application.Web.Controllers.SharedViewModels.PaymentItemViewModel
如果我这样调用,另一个模板确实有效:
@Html.DisplayFor(model => model.PaymentItems)
但是如果我指定模板名称:
@Html.DisplayFor(model => model.PaymentItems, "DisplayTemplates/PaymentItemViewModel.cshtml")
然后它失败了。就好像指定模板名称要么被完全忽略,要么破坏了模板功能。
最佳答案
Shelakel 对问题的评论为我回答了一半的问题。
我将“DisplayTemplates/PaymentItem”更改为“PaymentItem”,它开始调用正确的模板。但是,它确实引发了另一个问题,它提示它试图将 IList 传递到单个对象中。
这是 PaymentItems 在主模型上的样子:
private IList<PaymentItemViewModel> paymentItems = new List<PaymentItemViewModel>();
public IEnumerable<PaymentItemViewModel> PaymentItems
{
get { return paymentItems; }
set { paymentItems = value.ToList(); }
}
为了解决这个问题,我必须将显示模板上的模型设为 IList 并在其中放置一个 foreach。真的有点毫无意义,因为我认为模板的主要原因之一是您不需要在 View 上循环遍历集合!
无论如何,我认为 IList 问题源于初始集合作为 IList 开始的事实,但我现在已经开始工作了,所以我想问题已经得到解答。
更改来自 IList<PaymentItemViewModel
的 paymentItems 声明至 IEnumerable<PaymentItemViewModel>
不会改变任何东西。
关于c# - DisplayFor 不适用于具有不同命名空间的相同模型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14838450/