Asp.net mvc 3 mvc3对象引用未设置为对象的实例,无法解决此问题
我遇到一个错误,对象引用未设置为对象的实例我尝试了多种方法,但不断出现该错误,错误发生在这行代码上Asp.net mvc 3 mvc3对象引用未设置为对象的实例,无法解决此问题,asp.net-mvc-3,object-reference,Asp.net Mvc 3,Object Reference,我遇到一个错误,对象引用未设置为对象的实例我尝试了多种方法,但不断出现该错误,错误发生在这行代码上 @if(!string.IsNullOrWhiteSpace(Model.profile.photo)) { @Html.DisplayFor(x => x.profile.firstname) @Html.DisplayFor(x => x.profile.lastname) } else { <p>This user does no
@if(!string.IsNullOrWhiteSpace(Model.profile.photo))
{
@Html.DisplayFor(x => x.profile.firstname) @Html.DisplayFor(x => x.profile.lastname)
}
else {
<p>This user does not have a profile</p>
}
我的控制器是
public ActionResult detail(int id)
{
relisting relistings = db.relistings.Find(id);
var profiles = (from s in db.profiles where s.registrationID == relistings.RegistrationID select s).FirstOrDefault();
return View(new relist_profile {profile = profiles, relisting = relistings });
}
发生的情况是,当var配置文件与(s.registrationID!=relistings.registrationID)不匹配时,它会抛出错误,但如果存在一个配置文件,并且该配置文件匹配(TRUE),则一切都会正常工作。
如果注册ID没有匹配项,返回
null
,如何解决此问题。因此,public ActionResult detail(int-id)
中的profiles
为空,因此,null
被传递到视图中
当Model.profile
为空时,您无法访问Model.profile.photo
。尝试添加空检查:
@if(Model.profile != null &&
!string.IsNullOrWhiteSpace(Model.profile.photo))
{
//...
}
else {
<p>This user does not have a profile</p>
}
@if(Model.profile!=null&&
!string.IsNullOrWhiteSpace(Model.profile.photo))
{
//...
}
否则{
此用户没有配置文件
}
可能是型号.配置文件
==null???也就是说,detail(int-id)
中的profiles
为null FirstOrDefault将允许第一个匹配值或null,如果您在后续CAL中使用此调用的结果,则需要在执行任何操作之前检查其是否为null。如果调用First(),则该异常将在该语句中引发,因为它对单个结果有效。
@if(Model.profile != null &&
!string.IsNullOrWhiteSpace(Model.profile.photo))
{
//...
}
else {
<p>This user does not have a profile</p>
}