2017-04-10 61 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

相關問題