我无法在asp.net mvc的视图中传递IEnumerable ViewModel

时间:2017-04-10 08:02:18

标签: c# asp.net asp.net-mvc

我得到了这个例外,但我不知道如何修复它:

  

传递到字典中的模型项的类型是' System.Collections.Generic.List 1[DataModel.Gabarit]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [ViewModel.GabaritViewModel]'。

我的控制器:

 public ActionResult Traitement(string designation)
    {
       GabaritRepository gabaritrepository = new GabaritRepository(db);
        var gabarits = gabaritrepository.Get(g => g.Designation == designation).ToList();

        return View(gabarits);
    }

我的观点:

@model IEnumerable<ViewModel.GabaritViewModel>   
@{
    ViewBag.Title = "Traitement";
}

<h2>Traitement</h2>    
<div class="col-xs-12">
    <div class="box">
        <h2>Gabarits</h2>

        <table class="table table-striped">
            <tr>
                <th>
                    Code à barre
                </th>
                <th>
                   Etat
                </th>
                <th>                      
                </th>                  
            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.CodeBarre)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Etat)
                    </td>                                                                 
                    <td>    
                        @Html.ActionLink("Sortie", "Sortie", new {id = item.CodeBarre})                         
                    </td>
                </tr>
            }

        </table>
    </div>
</div>

GabaritViewModel:

   namespace ViewModel
{
    public class GabaritViewModel
    {
        public int CodeBarre { get; set; }
        public string Designation { get; set; }
        public string Photo { get; set; }
        public Nullable<int> Produit { get; set; }
        public Nullable<int> Poste { get; set; }
        public string Exemplaire { get; set; }
        public string Etat { get; set; }
        public int Id_Etat { get; set; }

       }

我必须传递ViewModel而不是DataModel而且我不知道为什么我不被允许。

1 个答案:

答案 0 :(得分:0)

您的存储库.Get()方法正在返回类型为Garbarit的集合,您需要一个类型为GabaritViewModel的集合。 一种选择是进行另一次选择并手动映射您的属性:

public ActionResult Traitement(string designation)
{
    GabaritRepository gabaritrepository = new GabaritRepository(db);
    var gabarits = gabaritrepository.Get(g => g.Designation == designation)
                                    //Map your Gabarit to your ViewModel here
                                    .Select(x => new GabaritViewModel {
                                        CodeBarre = x.CodeBarre,
                                        Etat = x.Etat
                                    }).ToList();

    return View(gabarits);
}