0

我正在尝试创建一个ViewModel. 对于我的应用程序,我想显示一个客户列表,其中他们的帐户存在错误。错误由另一个程序存储在数据库中。

最终目的是定期向其帐户中的项目有错误的客户发送消息(我们正在处理车辆,因此一个示例可能是车牌检查出现问题并需要客户采取行动) .

我创建了一个ViewModel名为 CustomerAlerts.cs

using MyProjectName.Models;

namespace MyProjectName.ViewModels
{
    public class CustomerAlerts
    {
        public IEnumerable<string> companynames { get; set; }
    }
}

我创建了一个控制器 CustomerAlertsController.cs。

private TestDB_FleetCompany_Dashboard_Entities db = new TestDB_FleetCompany_Dashboard_Entities();

public ActionResult Index()
{

    var viewModel = new CustomerAlerts
    {
        companynames = (from v in db.Vehicles.Include(v => v.Company)
                        where v.Issue != null
                        select new { customernames = v.Company.Name }).Select(v => v.customernames).AsEnumerable()
    };

    return View(viewModel);
}

在我的视野中,我有

@model IEnumerable<MyProjectName.ViewModels.CustomerAlerts>

我想显示受影响的公司名称列表(我打算稍后添加一列,用于计算有问题的车辆数量)。

@foreach (var affected in Model)
{
    <tr>
        <td>@Html.DisplayForModel(affected.companynames)</td>
        <td></td>
    </tr>
}

当我尝试运行所有内容时,我收到以下消息:

传入字典的模型项的类型为“MyProjectName.ViewModels.CustomerAlerts”,但此字典需要“System.Collections.Generic.IEnumerable`1[MyProjectName.ViewModels.CustomerAlerts]”类型的模型项。

虽然我喜欢一个解决方案或一点帮助,但我会很感激我应该阅读的内容,以帮助我自己找出解决方案。

我试过了:

return View(viewModel.AsEnumerable());

但这会导致“不包含 AsEnumerable 的定义”错误。

4

3 回答 3

1

您正在将单个实例传递CustomerAlerts给您的视图,但您的视图的模型类型是CustomerAlerts.

传递一个集合CustomerAlerts,或者将您的视图模型类型更改为:

@model MyProjectName.ViewModels.CustomerAlerts
于 2013-03-27T15:14:46.047 回答
1

这是因为您CustomerAlerts从您的Index方法中返回了您的单个实例,并且您的视图需要它的列表。

于 2013-03-27T15:14:52.527 回答
0

As per @devdigital above the answer that worked for me was to change the view model type to:

@model MyProjectName.ViewModels.CustomerAlerts

I did try this before, but was missing something else in the view that was causing an exception. The foreach statement needed some adjustment to this:

@foreach (var companyname in Model.companynames)
{
    <tr>
        <td>@companyname</td>
        <td>@companyname.Count()</td>
    </tr>
}

This now shows a handy list of the companies carrying errors and how many vehicles in their inventory are in an error state.

于 2013-03-28T09:07:57.460 回答