Foreach Sử dụng List khi ViewBag trong MVC bị lỗi FirstOrDefault() First()

Thảo luận trong 'Lập Trình Website MVC5 & MVC6' bắt đầu bởi seolagi, 5/8/18.

  1. seolagi
    Tham gia ngày:
    16/4/14
    Bài viết:
    1,028
    Đã được thích:
    80
    Điểm thành tích:
    48
    Khi mình gọi ViewBag.VBProduct trong hàm foreach của web MVC, sau đó mình select dữ liệu dạng FirstOrDefault() hoặc First() lấy vào các bảng phía trong thì bị báo lỗi. Giờ làm sao để chuyển ViewBag.VBProduct sang dạng list của Bảng dữ liệu tương ứng của ViewBag.VBProduct.
    Ví dụ: @foreach (var p in ViewBag.VBProduct as Product) //Báo lỗi.
    Lỗi:
    • 'System.Collections.Generic.HashSet<EShopV20.Models.SupDetail>' does not contain a definition for 'FirstOrDefault'
    • Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    • Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Collections.Generic.HashSet<EShopV20.Models.SupDetail>' does not contain a definition for 'First'
    Code của mình khi view:
    Mã:
    @foreach (var p in ViewBag.VBProduct)
    {
        <div class="cs-row10 cs-rowCl">
            <img class="col-lg-4 col-md-4 col-sm-4 col-xs-4" alt="" src="~/images/suppliers/@p.Category.SupDetails.FirstOrDefault().Logo" />
            <div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
                <a href="/Product/Detail/@p.Id"><h3>@p.Category.SupDetails.FirstOrDefault().Name</h3></a>
            </div>
        </div>
    }
    Giúp mình với, cảm ơn
     
    Cảm ơn đã xem bài:

    Foreach Sử dụng List khi ViewBag trong MVC bị lỗi FirstOrDefault() First()

  2. admin
    Tham gia ngày:
    22/5/13
    Bài viết:
    4,895
    Đã được thích:
    1,198
    Điểm thành tích:
    113
    Giới tính:
    Nam
    Hi bạn, bạn muốn sử dụng ViewBag.Model (VBProduct) trong hàm foreach để truy cập dữ liệu ở các dữ liệu khóa ngoại bảng khác thì bạn phải chuyển nó sang dạng list ICollection thì mới truy xuất được nhé.
    Bạn chỉ cần đổi cái foreach lại như sau:
    Mã:
    @foreach (var p in ViewBag.modelrelated as ICollection<Product>)
    {
        <div class="cs-row10 cs-rowCl">
            <img class="col-lg-4 col-md-4 col-sm-4 col-xs-4" alt="" src="~/images/suppliers/@p.Category.SupDetails.FirstOrDefault().Logo" />
            <div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
                <a href="/Product/Detail/@p.Id"><h3>@p.Category.SupDetails.FirstOrDefault().Name</h3></a>
            </div>
        </div>
    
    }