ASP.NET可以使用PartialViewResult检查模型的状态

时间:2013-10-04 18:37:35

标签: c# asp.net asp.net-mvc asp.net-mvc-partialview

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

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

控制器方法:     public PartialViewResult 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);
        }

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

1 个答案:

答案 0 :(得分:1)

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

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在您的情况下扮演的角色)应该完全不了解此视图逻辑。您的域模型不应与您的视图模型绑定。