2017-04-10 56 views
-3

我得到这个例外,但我不如何解决它:我能不能通过IEnumerable的视图模型在我看来,在asp.net mvc的

传递到字典的模型项的类型为“系统.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,我不知道为什么我不被允许。

+0

显示代码(属性)“返回查看(gabarits);” - 应该返回列表

+0

错误的哪部分你不明白,你的研究表明了什么?您必须在将'Gabarit'转换为'GabaritViewModel'实例之前将其传递给'return View(model)'。 – CodeCaster

+0

希望你的“gabarits”是一个列表包含项目,每个项目包含'GabaritViewModel'类的所有属性。我正确/如果错误,请显示单个项目的“gabarits”的值 –

回答

0

您的知识库.Get()方法正在返回一个类型为Garbarit的集合,您需要一个类型为GabaritViewModel的集合。 一种选择是另做选择和手动映射您的属性:为您GabaritViewModel类和UR控制器内部

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); 
} 
+0

这真的有帮助..非常感谢:) – oumaima

相关问题