在视图中检查模型是否有数据

时间:2018-06-03 15:42:06

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

问题

如何在视图本身内安全有效地检查视图模型是否已填充数据?


说明

我正在将模型传递给这样的视图;

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

如果有更好的方法可以解决这个问题,那么我愿意接受建议。我很感激帮助:)

1 个答案:

答案 0 :(得分:0)

如果您不确定他们是否拥有该值,您可以使用安全导航操作员(?。)来访问这些属性。

@Model?.CountOfUsers

查找更多详情here