简体   繁体   中英

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

The model item passed into the dictionary is of type '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]

The error message is self explanatory! In your LINQ expression, you are projecting the result to a list of annonymous objects and passing that to the view. But your view is strongly typed to a collection of Products class.

Change your anonymous object projection to the projection using Product class.

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);

视图是强类型的,并且要传递匿名类型,以创建一个列表项类,然后将其用作视图模型以将数据传递给视图。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM