2013-10-04 5 views
1

컨트롤러에서 데이터베이스의 일부 정보를 보유 할 모델을 만드는 방법이 있습니다. 메서드 내에서 로직을 만들 수있는 방법이 있습니까? 모델에 이미 데이터가 있습니까? 이 SelectCompanyFromDropdown()은 사용자가 다른 페이지로 이동할 때마다 호출되지만 확인하고 싶은 데이터베이스 호출을 줄이기 위해 호출됩니다. 전역 변수가 트릭을 수행하는지 궁금하지만, 전역 디버깅에 문제가 발생할 수 있습니다.ASP.NET PartialViewResult가 모델의 상태를 확인할 수 있습니까?

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

컨트롤러 방법 : 공공 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

마음에 가장 먼저 떠오르는 것은 필수 입력란을 확인하는 것입니다. 입력란은 필수 입력란에 입력해야합니다. 그래서 Model.mandatoryField! = null이라면 ... – RealityDysfunction

+0

사실 나는 그냥 가서 데이터를 캐싱 한 다음 캐시 된 객체에 대한 검사를 수행했습니다. –

답변

1

데이터베이스 호출의 결과가 자주 변경되지 않으면 캐시 할 수 있습니다. 그래서이 작업을 수행하는 방법을 작성하여 시작합니다

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

당신이 보인다 : 이제 모든

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

와 컨트롤러 액션에 남아 뷰 모델을 채우기 위해이 메소드를 호출하는 것입니다 보기 모델에 대한 오해가 있습니다. 귀하의 EF 컨텍스트는 CompanyViewModelDbContext 인 것으로 보입니다. 뷰 모델은 뷰 논리의 요구 사항을 충족하도록 특별히 설계된 클래스입니다. 귀하의 데이터 계층 (귀하의 경우 EF가 역할을 수행하는 영역)은이 뷰 로직에 대한 지식이 전혀 없어야합니다. 도메인 모델은 뷰 모델에 묶여서는 안됩니다.

+0

그래서 뷰 ​​모델은 뷰에 전달되는 정보 만 보유해야한다는 말입니까? 데이터베이스 로직이 없다면? 이것이 내가 결국 구현 한 것입니다. –