在MVC5视图中处理/防止NullReferenceException?

时间:2014-06-17 15:31:15

标签: c# asp.net-mvc asp.net-mvc-5 nullreferenceexception entity-framework-6

我有一个使用Grid.MVC显示所需用户属性的视图。我的控制器使用User [MemberOrgID]或[SponsorOrgID]来查找与该用户特定ID相关的所有相关组织/赞助商信息(用户将拥有其中一个ID,而不是两者):

    // GET: Admin/UserManagement
    public async Task<ActionResult> Index()
    {
        ViewBag.headerTitle = "User Management";
        ViewBag.showCreateButton = true;
        ViewBag.createUrl = "/Admin/UserManagement/Create";
        ViewBag.createText = " Create a New User";
        List<ApplicationUser> model = UserManager.Users.ToList();
        foreach (ApplicationUser user in model)
        {
            if (user.MemberOrgId != null)
            {
                user.Organization = db.MemberOrganizations.Find(user.Organization);
            }
            //else
            //{
            //    user.Organization.Name = " ";
            //}

            if (user.SponsorOrgId != null)
            {
                user.Sponsor = db.SponsorOrganizations.Where(o => o.Id == user.SponsorOrgId).FirstOrDefault();
            }
            //else
            //{
            //    user.Sponsor.Name = " ";
            //}
        }
        return View(model);
    }

由于我的第一个用户有一个赞助商ID,这是我在VS2013中调试时在立即窗口中可以看到的:

?user.Sponsor
    {System.Data.Entity.DynamicProxies.SponsorOrganizations_F2A27693F33AFF36C814F6FFA2CE63AD656938244F599B7D1AB2ED80CC26EF9A}
    [System.Data.Entity.DynamicProxies.SponsorOrganizations_F2A27693F33AFF36C814F6FFA2CE63AD656938244F599B7D1AB2ED80CC26EF9A]: {System.Data.Entity.DynamicProxies.SponsorOrganizations_F2A27693F33AFF36C814F6FFA2CE63AD656938244F599B7D1AB2ED80CC26EF9A}
    City: null
    Country: null
    Enabled: true
    FacebookUrl: "https://www.facebook.com/sponsor1"
    Id: 1
    LogoSrc: "Sponsor1.jpg"
    Name: "Sponsor1"
    OwnerId: "1d720c20-a508-4880-a5e6-80af5f2f8caf"
    OwnerName: "Sponsor Primary"
    ProfilePictureUrl: "sponsorprofilepicture/Sponsor1.jpg"
    SponsorServiceCategory: Count = 11
    State: null
    TwitterUrl: "https://twitter.com/sponsor1"
    Users: Count = 0
    WebsiteUrl: "http://www.sponsor1.com"

我有一个NullReference问题但是当加载View时(下面)代码o.Organization.Name被标记为NullReferenceException(我添加了一个try catch只是为了让事情变得更友好一些让其余的View加载):

@using GridMvc.Html
@model IEnumerable<PROJECTS.Models.ApplicationUser>

@{
    ViewBag.Title = "View Users";
    Layout = "~/Areas/Admin/Views/Shared/_LayoutAdmin.cshtml";

}

<div class="overflowPrevention">
    <!-- Grid.MVC Code -->
    <div>
        @*Images in Columns: https://gridmvc.codeplex.com/discussions/440977*@
@try
{ 
        @Html.Grid(Model).Columns(columns =>
        {
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => Html.ActionLink("Edit", "Edit", "UserManagement", new { id = o.Id }, null)).SetWidth(15);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Name).Titled("Name").Sortable(true).Filterable(true).SetWidth(100);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Position).Titled("Position").Sortable(true).Filterable(true).SetWidth(50);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Email).Titled("Email").Sortable(true).Filterable(true).SetWidth(100);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.EmailConfirmed.ToString()).Titled("Confirmed").Sortable(true).Filterable(true).SetWidth(100);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.MemberOrgId.ToString()).Titled("MemOrg.").Sortable(true).Filterable(true).SetWidth(25);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Organization.Name.ToString()).Titled("MemOrg.").Sortable(true).Filterable(true).SetWidth(25);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.SponsorOrgId.ToString()).Titled("Sponsor").Sortable(true).Filterable(true).SetWidth(25);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Sponsor.Name.ToString()).Titled("Sponsor").Sortable(true).Filterable(true).SetWidth(25);
        }).WithPaging(5)
}
catch (NullReferenceException ex)
{
    return;
}
    </div>
</div>

有没有人想过如何否定这个NullReferenceException问题?用户将始终拥有MemberOrganizationID或SponsorID,这意味着o.Organization.Name将具有值或o.Sponsor.Name将是,但从不两者。我正试图找到一种方法来使一个为空的,或者不显示,或者只是在列中显示为空白值。

任何帮助非常感谢!我试图通过我的Controller上的一些IF检查以及View上的一些代码来否定这个问题,但还没有找到解决方案。

修改

克里斯的解决方案奏效了!以下是我更新的代码段:

foreach (ApplicationUser user in model)
        {
            if (user.MemberOrgId != null)
            {
                user.Organization = db.MemberOrganizations.Where(o => o.Id == user.MemberOrgId).FirstOrDefault();
            }
            if (user.SponsorOrgId != null)
            {
                user.Sponsor = db.SponsorOrganizations.Where(o => o.Id == user.SponsorOrgId).FirstOrDefault();
            }
        }
        return View(model);

        columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.MemberOrgId.ToString()).Titled("MemOrgID").Sortable(true).Filterable(true).SetWidth(25);
        columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Organization == null ? "" : o.Organization.Name.ToString()).Titled("MemOrg Name.").Sortable(true).Filterable(true).SetWidth(25);
        columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.SponsorOrgId.ToString()).Titled("SponsorID").Sortable(true).Filterable(true).SetWidth(25);
        columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Sponsor == null ? "" : o.Sponsor.Name.ToString()).Titled("Sponsor Name").Sortable(true).Filterable(true).SetWidth(25);

1 个答案:

答案 0 :(得分:3)

在尝试获取名称之前检查空组织?

columns.Add().Encoded(false).Sanitized(false)
    .RenderValueAs(o => o.Organization == null ? "" : o.Organization.Name.ToString())
    .Titled("MemOrg.").Sortable(true).Filterable(true).SetWidth(25);

如果要将它们合并为一个列,请修改上述代码,以便在组织为空时返回赞助商名称。