Domanda

I am getting an error of Object reference not set to an instance of an object I have tried multiple things but keep getting that error, the error is occuring on this line of code

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

@if(!string.IsNullOrWhiteSpace(Model.profile.photo))

I have a view that contains 2 models as

public class relist_profile
{
    public relisting relisting { get; set; }
    public profile profile { get; set; }

}

and my controller is

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

what is occuring is that when the var profiles doesn't match up (s.registrationID != relistings.RegistrationID) then it throws the error but if there is a PROFILE and it matches(TRUE) then everything works perfectly. How can I resolve this issue

È stato utile?

Soluzione

When there is no match by registrationID, Enumerable.FirstOrDefault returns null. So profiles in public ActionResult detail(int id) is null then and null is consequently passed into the view.

You cannot access Model.profile.photo, when Model.profile is null. Try to add null check:

@if(Model.profile != null && 
    !string.IsNullOrWhiteSpace(Model.profile.photo))
{
    //... 
}
else {
   <p>This user does not have a profile</p>
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top