ASP.NET 部分视图结果可以检查模型的状态

本文关键字:检查 模型 状态 结果 NET 视图 ASP | 更新日期: 2023-09-27 18:33:53

在我的控制器中,我有一个方法,它正在创建一个模型来保存数据库中的一些信息,有没有办法在方法中创建一些逻辑来检查模型中是否已经有数据? 每次用户导航到另一个页面时都会调用此SelectCompanyFromDropdown(),但为了减少数据库调用,我想检查一下。我想知道全局变量是否可以解决问题,但我知道您可能会在调试全局变量时遇到麻烦。

pseudo: 
if(Model != null)
Run Method
return PartialView(new model)
Else
return PartialView(existing model)

控制器方法: public PartViewResult SelectCompanyFromDropdown() {

            var coid = Lt.GetThisUsersCoId();
            var model = new CompanyViewModel();
            using (var dc = new CompanyViewModelDbContext())
            {
                var content =
                    (from cr in db.CompanyRelationship
                     //This is grabbing all related companies to the logged in user
                     join c in db.Companies on cr.CoId equals c.CoId
                     where cr.PartnerCoId == coid
                     select new
                     {
                         cr.CoId,
                         c.CompanyName
                     }).Distinct().ToDictionary(cr => cr.CoId, c => c.CompanyName);
                model.Companies = content;
            }
            return PartialView(model);
        }

这是将模型发送到视图以创建一个下拉列表,但是我想在每次用户更改页面时仅引用现有模型。

ASP.NET 部分视图结果可以检查模型的状态

如果数据库调用的结果不会经常更改,则可以缓存它。因此,首先编写一个将执行此任务的方法:

private IDictionary<int, string> GetCompanies(int coid)
{
    var result = MemoryCache.Default[coid.ToString()] as IDictionary<int, string>;
    if (result != null)
    {
        // we already have cached results => no need to perform expensive database calls
        // we can return directly the cached results;
        return result;
    }
    // there's nothing in the cache => we need to make the DB call
    // and cache the results for subsequent use
    using (var dc = new CompanyViewModelDbContext())
    {
        result =
            (from cr in db.CompanyRelationship
             //This is grabbing all related companies to the logged in user
             join c in db.Companies on cr.CoId equals c.CoId
             where cr.PartnerCoId == coid
             select new
             {
                 cr.CoId,
                 c.CompanyName
             }).Distinct().ToDictionary(cr => cr.CoId, c => c.CompanyName);
    }
    var policy = new CacheItemPolicy
    {
        // Cache the results of the Db query for 24 hours
        AbsoluteExpiration = DateTimeOffset.Now.AddHours(24),
        Priority = CacheItemPriority.NotRemovable,
    };
    MemoryCache.Default.Set(coid.ToString(), result, policy);
    return result;
}

现在,控制器操作中剩下的就是调用此方法来填充视图模型:

var model = new CompanyViewModel();
var coid = Lt.GetThisUsersCoId();
model.Companies = GetCompanies(coid);
return PartialView(model);

此外,您似乎对视图模型有一些误解。您的 EF 上下文似乎称为 CompanyViewModelDbContext 。视图模型是专门为满足视图逻辑的要求而设计的类。数据层(EF 在你的案例中扮演的角色)应该完全不知道此视图逻辑。域模型不应绑定到视图模型。