问题
如何在视图本身内安全有效地检查视图模型是否已填充数据?
的说明
我正在将模型传递给这样的视图;
return View(response.Success ? (SalesDashboardViewModel)response.Model : new SalesDashboardViewModel());
现在,视图要么具有包含所有数据的完全填充的视图模型,要么,如果视图模型未正确填充,则它可能具有空的“SalesDashboardViewModel”。如果第二种情况属实,例如,当我在视图中调用@Model.CountOfUsers
时,我会收到null object reference
错误。
在视图中,我将如何检查这是否为空,除了检查其中一个属性是否为空(由于属性可能会发生变化)。
完整代码突破
//控制器
public ActionResult SalesDashboard(){
var response = DashboardService.BuildSalesViewModel(User.Identity.GetUserId());
return View(response.Success ? response.Model : new SalesDashboardViewModel());
}
//填充SalesDashboardViewModel
public CustomResponseModel BuildSalesViewModel(string userId)
{
try
{
CustomResponseModel response;
var vm = new SalesDashboardViewModel();
response = GetCountOfSuspectsAddedThisMonth(userId);
vm.NoSuspectsAddedThisMonth = response.Success ? (int)response.Model : throw new Exception(response.Reason);
response = GetCountOfProspectsAddedThisMonth(userId);
vm.NoPropectsAddedThisMonth = response.Success ? (int)response.Model : throw new Exception(response.Reason);
response = GetCountOfCustomersNotContactedRecently(userId, 12);
vm.NoCustomersNotContactedRecently = response.Success ? (int)response.Model : throw new Exception(response.Reason);
response = GetTopProspects(userId, 10);
vm.TopProspects = response.Success ? (List<Prospect>)response.Model : throw new Exception(response.Reason);
return new CustomResponseModel { Success = true, Model = vm };
}
catch (Exception e)
{
return new CustomResponseModel
{
Success = false,
Reason = e.Message,
};
}
}
如果有更好的方法可以解决这个问题,那么我愿意接受建议。我很感激帮助:)