2011-05-14 198 views
-2

我在控制器中寫了類似這樣的東西。ASP.NET Mvc問題

public ActionResult Giris() 

    { 

     ViewData["Tarif"] = (from t in _entities.Tarif 

          join k in _entities.Kullanici on t.KID equals k.KID 

          select new {KAdi = k.KAdi, TAdi = t.TAdi}) 

          .Take(4); 



     return View(); 

    } 

我在查看頁面中使用它。

<% foreach (var item in (IEnumerable<dynamic>)ViewData["Tarif"]) { %> 

<div class="begenilen-video" style="float:left"> 

<img class="video-resmi" alt="reklam" src="../../Uygulama/Resimler/Reklam/1.jpg" /> 

<span class="benzer-yemek-tarifi-adi"></span><%=item.TAdi %><br /> 

<span class="benzer-yemek-tarifi-ekleyen">Ekleyen: </span><br /> 

<span class="benzer-yemek-tarifi-izlenme">İzlenme: </span> 

</div> 

<% } %> 

但是,我在select語句中收到錯誤。如何調用視圖頁中的項目?

在此先感謝。

+4

什麼是錯誤? – Rob 2011-05-14 10:18:25

回答

1

作爲一個猜測,因爲你還沒有張貼的錯誤:

對象存儲在ViewData["Tarif"]將是類型IQueryable<T>其中T是一個匿名的對象,並在你看來你是鑄造IEnumerable<dynamic>的。 IQueryable也被延遲加載,所以你會試圖在對象被處置後執行你的查詢。

你真的應該創建一個強類型的視圖模型

public class ViewModelType { 

    public IEnumerable<TarifType> Tarif { get; set; } 

} 

塔裏夫型

public class TarifType { 

    public string KAdi { get; set; } 
    public string TAdi { get; set; } 

} 

控制器

public ActionResult Giris() { 

    var viewModel = new ViewModelType(); 

    viewModel.Tarif = (from t in _entities.Tarif 
         join k in _entities.Kullanici on t.KID equals k.KID 
         select new TraifType { KAdi = k.KAdi, TAdi = t.TAdi } 
        ).Take(4) 
        .ToList(); 

    return View(viewModel); 
} 

視圖

<% foreach (var item in viewModel.Tarif) { %> 
    <div class="begenilen-video" style="float:left"> 
    <img class="video-resmi" alt="reklam" src="../../Uygulama/Resimler/Reklam/1.jpg" /> 
    <span class="benzer-yemek-tarifi-adi"></span><%=item.TAdi %><br /> 
    <span class="benzer-yemek-tarifi-ekleyen">Ekleyen: </span><br /> 
    <span class="benzer-yemek-tarifi-izlenme">İzlenme: </span> 
    </div> 
<% } %>