簡體   English   中英

MVC 5中的異常,模型未在視圖中傳遞數據

[英]exception in mvc 5, model is not passing data in view

  public ActionResult CustomerOrders()
    {
        string cookieName = FormsAuthentication.FormsCookieName; //Find cookie name
        HttpCookie authCookie = HttpContext.Request.Cookies[cookieName]; //Get the cookie by it's name
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); //Decrypt it
        string UserName = ticket.Name;
        int UserID = context.Registers.Where(x => x.name == UserName).Select(x => x.id).FirstOrDefault();

       var data = (from i in context.Registers.Where(x => x.id == UserID)
                             join
                              c in context.Orders on i.id equals c.customer_id
                             into egroup
                             from k in egroup
                             join p in context.Products
                             on k.product_id equals p.product_id
                             select new
                             {
                                 p.price,
                                 // k.order_total,
                                 p.ImageUrl,
                                 p.ProductName

                             }).ToList() ;
        Products pr = new Products();

        return View(data);
       // return View(data);
    }

傳遞到字典中的模型項的類型為'System.Collections.Generic.List 1[<>f__AnonymousType3 3 [System.Nullable 1[System.Int32],System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [PetsApplication.Models.Products] 1[System.Int32],System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable

錯誤消息不言自明! 在LINQ表達式中,您將結果投影到一個匿名對象列表中,並將其傳遞給視圖。 但是,您的視圖強烈屬於Products類的集合。

使用Product類將匿名對象投影更改為投影。

var data = (from i in context.Registers.Where(x => x.id == UserID)
            join c in context.Orders on i.id equals c.customer_id
            into egroup
            from k in egroup
            join p in context.Products
            on k.product_id equals p.product_id
            select new Products
            {
                price=p.price,                   
                ImageUrl=p.ImageUrl,
                ProductName=p.ProductName

            }).ToList();
 return View(data);

視圖是強類型的,並且要傳遞匿名類型,以創建一個列表項類,然后將其用作視圖模型以將數據傳遞給視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM