Home > front end >  System.NullReferenceException while creating a Details View Site Model that has a field from Region
System.NullReferenceException while creating a Details View Site Model that has a field from Region

Time:07-08

Details.cshtml (For Site)

This is the part of the code causing problem

<b>Region: </b>
<a asp-controller="Regions" asp-action="Details" asp-route-id="@Model.RegionID">
@Model.Region.Name
</a>
</p>

my site model has a field called RegionID which represents the region in which the site is located and when i am trying to retrieve the Region name to display it in the details view of the site i am getting the System.NullReferenceException

Any Idea on how i can solve this issue would be appreciatedenter image description here

CodePudding user response:

you have to fix you ef code in Details action

var model= await context...
.Include(r=> r.Region)
...

CodePudding user response:

You can try to set a default value for Model.Region:

public class YourModel{
    public int RegionID { get; set; }
    public Region Region { get; set; } = new Region();
}
public class Region {
    public string Name { get; set; }
}
  • Related