Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 3 mvc3对象引用未设置为对象的实例,无法解决此问题_Asp.net Mvc 3_Object Reference - Fatal编程技术网

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