本文介绍了传递到字典中的模型项的类型为.... {Models.App},但我传递的是{Models.App,System.Double}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有一个查询,该查询可以获取所有应用程序,并包括来自另一个表的平均评分

I have a query in my controller that gets all the apps, and includes their average rating from another table

var apps = from a in db.Apps
           let rating = a.Ratings.Average(r => r.Stars)
           select new { App = a, Rating = rating == null ? 0 : rating };

然后我根据从家里通过的过滤器来订购它们.没什么大不了的.

Then I order them based on which filter is passed from home....no big deal....

switch (sortOrder)
        {
            case "Top desc":
                apps = apps.OrderByDescending(a => a.Rating);
                break;
            case "Newest":
                apps = apps.OrderBy(a => a.App.DateUpdated);
                break;
            case "Newest desc":
                apps = apps.OrderByDescending(a => a.App.DateUpdated);
                break;
            default:
                apps = apps.OrderBy(a => a.Rating);
                break;
        }

然后将其返回到视图

return View(apps.ToPagedList(pageIndex, pageSize));

但是,在主页上我收到一条错误消息,指出我传递了错误类型的模型Item,传递了{Model.App,System. Double}(我想是因为查询添加了平均评分"的方式……我如何仍能获得平均评分,但要发回正确的模型项类型.谢谢!

However, on the home page I get an error stating I am passing the wrong type of model Item, I am passing {Model.App, System. Double} ( I assume because of the way my query adds the Rating Average......How can I still get a rating average, but send back the proper model item type. Thanks!

推荐答案

不要在您的视图中传递匿名类型.定义视图模型:

Don't pass anonymous types in your views. Define view models:

public class MyViewModel
{
    public App App { get; set; }
    public double Rating { get; set; }
}

然后:

var apps = 
    from a in db.Apps
    let rating = a.Ratings.Average(r => r.Stars)
    select new MyViewModel 
    { 
        App = a, 
        Rating = rating == null ? 0 : rating 
    };

,然后在此视图模型中强烈键入您的视图.

and then strongly type your view to this view model.

@model PagedList.IPagedList<MarketplaceFinal.Models.MyViewModel>

这篇关于传递到字典中的模型项的类型为.... {Models.App},但我传递的是{Models.App,System.Double}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 12:16