【发布时间】:2019-03-14 01:46:54
【问题描述】:
我有一个简单的详细信息视图,如果用户是Customer,它使用两个 if 语句,它会显示客户属性。如果用户是Investor,则会显示他们的属性。
我的问题是我的 if 语句适用于其中之一,但不能同时适用。给我一个:
NullReferenceException:对象引用未设置为对象的实例
当尝试同时使用两个 if 语句时。
我的看法
@model MyProject.Models.ApplicationUser
<h3>
@Html.DisplayFor(m => Model.FirstName)
@Html.DisplayFor(m => Model.LastName)
</h3>
@if (Model.Customer.CustomerId != null)
{
<div class="form-group">
<strong>Tax ID:</strong>
@Html.DisplayFor(m => m.Customer.TaxId)
</div>
} else {
}
@if (Model.Investor.InvestorId != null)
{
<div class="form-group">
<strong>Social Security #:</strong>
@Html.DisplayFor(m => m.Investor.SsnNum)
</div>
<div class="form-group">
<strong>Date of birth:</strong>
@Html.DisplayFor(m => m.Investor.DOB)
</div>
} else {
}
控制器
public async Task<IActionResult> Details(string id)
{
if (id == null || id.Trim().Length == 0)
{
return NotFound();
}
var userFromDb = await _db.ApplicationUser.Include(u => u.Investor).Include(u => u.Customer).FirstOrDefaultAsync(i => i.Id == id);
if (userFromDb == null)
{
return NotFound();
}
return View(userFromDb);
}
投资者
public class Investor
{
[Key, ForeignKey("ApplicationUser")]
public string InvestorId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
[Required]
[Display(Name = "SSN")]
public string SsnNum { get; set; }
[Display(Name = "Date of Birth")]
public DateTime DOB { get; set; }
}
【问题讨论】:
-
向我们展示您如何填充
Customer和Investor。我怀疑其中一个没有初始化,因此你会得到 NULL 引用错误。 -
用
if (Model.Customer != null && Model.Customer.CustomerId != null)代替if (Model.Customer.CustomerId != null)。 -
该视图与 if 语句一起使用,直到我同时使用两个 if 语句然后它会引发错误。我可以将 if 语句用于投资者并且它有效或客户并且它有效,但不能同时使用。
-
因为一个或另一个 always 为空。它要么拥有
Customer,要么拥有Investor,但绝不会两者兼而有之。您应该像@WiktorZychla 建议的那样编写Model.Customer != null && Model.Customer.CustomerId != null之类的条件。也可以使用Model.Customer?.CustomerId != null之类的空条件运算符,这样更简单一些。
标签: c# asp.net-mvc razor