c# – Display related data in Razor View

I’m having trouble retrieving related data in my Details Razor View Page.

I have several Tables in my project but the two listed here (Applications and States) is what I’m having trouble with.

The trouble I’m having is that I need to retrieve the StateInt value for the ID that is in the AppTenantState field within the Applications Table. The Applications Table contains a field called StateId, that StateId is a value I stored for the Renter. I needed another field called AppTenantState to store the StateId value for the Tenant if applicable.

I’m going to post the Models for each along with the ViewModel, Controller and Razor Page that I’m using. Perhaps it’s a simple mistake on my part that someone can assist me with.

Application Model

    public class Application
{
    public int ApplicationId { get; set; }
    public string AppFirstName { get; set; }
    public string AppLastName { get; set; }
    public string AppAddress { get; set; }
    public string AppCity { get; set; }
    public string AppZipCode { get; set; }
    public DateTime AppDateOfBirth { get; set; }
    public string AppPhoneNumber { get; set; }
    public string AppEmailAddress { get; set; }
    public string AppEmployerName { get; set; }
    public string AppEmployerPhoneNumber { get; set; }
    public string AppEmploymentLength { get; set; }
    public decimal AppEmploymentGrossIncome { get; set; }


    public string AppTenantFirstName { get; set; }
    public string AppTenantLastName { get; set; }
    public string AppTenantAddress { get; set; }
    public string AppTenantCity { get; set; }
    public int? AppTenantState { get; set; }
    public string AppTenantZipCode { get; set; }
    public DateTime? AppTenantDateOfBirth { get; set; }
    public string AppTenantPhoneNumber { get; set; }
    public string AppTenantEmailAddress { get; set; }
    public string AppTenantEmployerName { get; set; }
    public string AppTenantEmployerNamePhoneNumber { get; set; }
    public string AppTenantLengthOfEmployment { get; set; }
    public decimal? AppTenantMonthlyGrossIncome { get; set; }


    public string AppPresentLandlord { get; set; }
    public string AppPresentLandlordPhoneNumber { get; set; }
    public int AppTotalPersonsOccupy { get; set; }
    public int AppTotalChildrenOccupy { get; set; }
    public bool AppAgreeToTerms { get; set; }
    public DateTime AppCreatedDate { get; set; }

    public int StateId { get; set; }
    public State State { get; set; }

    public int SmokerId { get; set; }
    public Smoker Smoker { get; set; }

    public int PetId { get; set; }
    public Pet Pet { get; set; }

    public int EvictionId { get; set; }
    public Eviction Eviction { get; set; }
}

State Model

public class State
{
    public int StateId { get; set; }
    public string StateInt { get; set; }
    public string StateName { get; set; }

    public ICollection<Application> Applications { get; set; }
}

ApplicationDetailsByIdViewModel ViewModel

    public class ApplicationDetailsByIdViewModel
{
    public int ApplicationId { get; set; }
    public Application Applications { get; set; }
    public List<State> States { get; set; }
    public IEnumerable<Smoker> Smokers { get; set; }
    public IEnumerable<Pet> Pets { get; set; }
    public IEnumerable<Eviction> Evictions { get; set; }
}

Fluent Api

        public DbSet<Application> Applications { get; set; }
    public DbSet<State> States { get; set; }
    public DbSet<Smoker> Smokers { get; set; }
    public DbSet<Pet> Pets { get; set; }
    public DbSet<Eviction> Evictions { get; set; }
    public DbSet<ApplicationUser> ApplicationUser { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        // Begin Application Database Table Schema
        builder.Entity<Application>()
            .HasKey(a => a.ApplicationId);

        builder.Entity<Application>()
            .Property(a => a.AppFirstName)
            .HasColumnType("varchar(25)")
            .HasMaxLength(25)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppLastName)
            .HasColumnType("varchar(25)")
            .HasMaxLength(25)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppAddress)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppCity)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppZipCode)
            .HasColumnType("varchar(5)")
            .HasMaxLength(5)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppDateOfBirth)
            .HasColumnType("date")
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppPhoneNumber)
            .HasColumnType("varchar(12)")
            .HasMaxLength(12)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppEmailAddress)
            .HasColumnType("varchar(255)")
            .HasMaxLength(255)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppEmployerName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppEmployerPhoneNumber)
            .HasColumnType("varchar(12)")
            .HasMaxLength(12)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppEmploymentLength)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppEmploymentGrossIncome)
            .HasColumnType("decimal(18,2)")
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppTenantFirstName)
            .HasColumnType("varchar(25)")
            .HasMaxLength(25)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantLastName)
            .HasColumnType("varchar(25)")
            .HasMaxLength(25)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantAddress)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantCity)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantState)
            .HasColumnType("int")
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantZipCode)
            .HasColumnType("varchar(5)")
            .HasMaxLength(5)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantDateOfBirth)
            .HasColumnType("date")
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantPhoneNumber)
            .HasColumnType("varchar(12)")
            .HasMaxLength(12)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantEmailAddress)
            .HasColumnType("varchar(255)")
            .HasMaxLength(255)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantEmployerName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantEmployerNamePhoneNumber)
            .HasColumnType("varchar(12)")
            .HasMaxLength(12)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantLengthOfEmployment)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppTenantMonthlyGrossIncome)
            .HasColumnType("decimal(18,2)")
            .IsRequired(required: false);

        builder.Entity<Application>()
            .Property(a => a.AppPresentLandlord)
            .HasColumnType("varchar(50")
            .HasMaxLength(50)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppPresentLandlordPhoneNumber)
            .HasColumnType("varchar(12")
            .HasMaxLength(12)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppTotalPersonsOccupy)
            .HasColumnType("int")
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppTotalChildrenOccupy)
            .HasColumnType("int")
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppAgreeToTerms)
            .IsRequired();

        builder.Entity<Application>()
            .Property(a => a.AppCreatedDate)
            .HasColumnType("datetime2")
            .HasDefaultValueSql("SYSDATETIME()")
            .ValueGeneratedOnAddOrUpdate()
            .IsRequired();

        // Begin One-To-Many Relationship Between Application and State
        builder.Entity<Application>()
            .HasOne(a => a.State)
            .WithMany(s => s.Applications)
            .HasForeignKey(a => a.StateId)
            .OnDelete(DeleteBehavior.Restrict);

        // Begin One-To-Many Relationship Between Application and Smoker
        builder.Entity<Application>()
            .HasOne(a => a.Smoker)
            .WithMany(sm => sm.Applications)
            .HasForeignKey(a => a.SmokerId)
            .OnDelete(DeleteBehavior.Restrict);

        // Begin One-To-Many Relationship Between Application and Pet
        builder.Entity<Application>()
            .HasOne(a => a.Pet)
            .WithMany(p => p.Applications)
            .HasForeignKey(a => a.PetId)
            .OnDelete(DeleteBehavior.Restrict);

        // Begin One-To-Many Relationship Between Application and Eviction
        builder.Entity<Application>()
            .HasOne(a => a.Eviction)
            .WithMany(e => e.Applications)
            .HasForeignKey(a => a.EvictionId)
            .OnDelete(DeleteBehavior.Restrict);

        // End Application Database Table Schema




        // Begin State Database Table Schema
        builder.Entity<State>()
            .HasKey(s => s.StateId);

        builder.Entity<State>()
            .Property(s => s.StateInt)
            .HasColumnType("varchar(2)")
            .HasMaxLength(2)
            .IsRequired();

        builder.Entity<State>()
            .Property(s => s.StateName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();
        // End State Database Table Schema


        // Begin Smoker Database Table Schema
        builder.Entity<Smoker>()
            .HasKey(sm => sm.SmokerId);

        builder.Entity<Smoker>()
            .Property(sm => sm.SmokerQuestion)
            .HasColumnType("varchar(3)")
            .HasMaxLength(3)
            .IsRequired();
        // End Smoker Database Table Schema


        // Begin Pet Database Table Schema
        builder.Entity<Pet>()
            .HasKey(p => p.PetId);

        builder.Entity<Pet>()
            .Property(p => p.PetQuestion)
            .HasColumnType("varchar(3)")
            .HasMaxLength(3)
            .IsRequired();
        // End Pet Database Table Schema

        // Begin Eviction Database Table Schema
        builder.Entity<Eviction>()
            .HasKey(e => e.EvictionId);

        builder.Entity<Eviction>()
            .Property(e => e.EvictionQuestion)
            .HasColumnType("varchar(3")
            .HasMaxLength(3)
            .IsRequired();
        // End Eviction Database Table Schema
    }

ApplicationController

public class ApplicationController : Controller
{
    private readonly ApplicationDbContext _db;
    public ApplicationController(ApplicationDbContext db)
    {
        _db = db;
    }


    // GET: /Applications
    public IActionResult Index()
    {
        IEnumerable<Application> objList = _db.Applications;
        return View(objList);
    }


    // GET: /Details/id
    public IActionResult Details(int? applicationId)
    {
        if (applicationId == null)
        {
            return NotFound();
        }

        var model = new ApplicationDetailsByIdViewModel
        {
            Applications = _db.Applications
            .Include(s => s.State)
            .Include(sm => sm.Smoker)
            .Include(p => p.Pet)
            .Include(e => e.Eviction)
            .FirstOrDefault(r => r.ApplicationId == applicationId)
    };
        return View(model);
    }

    // GET: /Details/id
    public IActionResult Delete(int? applicationId)
    {
        if (applicationId == null || applicationId == 0)
        {
            return NotFound();
        }

        Application applicationObj = _db.Applications.Include(s => s.State).FirstOrDefault(a=> a.ApplicationId == applicationId);
        
        if (applicationObj == null)
        {
            return NotFound();
        }

        return View(applicationObj);
    }


    [HttpPost,ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public IActionResult DeletePost(int? applicationId)
    {
        var applicationObj = _db.Applications.Find(applicationId);
        if (applicationObj == null)
        {
            return NotFound();
        }

        _db.Applications.Remove(applicationObj);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
}

Details RazorView

@model PRB.ViewModels.ApplicationDetailsByIdViewModel

<section class="details-container">
<div class="details">
    <div class="fullname">
        <span class="details-span">Full Name</span>
    </div>
    <div class="fullname-value">
        @Html.DisplayFor(model => model.Applications.AppFirstName) @Html.DisplayFor(model => model.Applications.AppLastName)
    </div>
    <div class="address">
        <span class="details-span">Address</span>
    </div>
    <div class="address-value">
        @Html.DisplayFor(model => model.Applications.AppAddress), @Html.DisplayFor(model => model.Applications.AppCity), @Html.DisplayFor(model => model.Applications.State.StateInt) @Html.DisplayFor(model => model.Applications.AppZipCode)
    </div>
    <div class="dob">
        <span class="details-span">Date of Birth</span>
    </div>
    <div class="dob-value">
        @Model.Applications.AppDateOfBirth.ToString("MM/dd/yyyy")
    </div>
    <div class="phone">
        <span class="details-span">Phone Number</span>
    </div>
    <div class="phone-value">
        @Html.DisplayFor(model => model.Applications.AppPhoneNumber)
    </div>
    <div class="email">
        <span class="details-span">Email Address</span>
    </div>
    <div class="email-value">
        @Html.DisplayFor(model => model.Applications.AppEmailAddress)
    </div>
    <div class="employername">
        <span class="details-span">Name of Employer</span>
    </div>
    <div class="employername-value">
        @Html.DisplayFor(model => model.Applications.AppEmployerName)
    </div>
    <div class="employerphone">
        <span class="details-span">Phone Number</span>
    </div>
    <div class="employerphone-value">
        @Html.DisplayFor(model => model.Applications.AppEmployerPhoneNumber)
    </div>
    <div class="lengthemployment">
        <span class="details-span">Length of Employment</span>
    </div>
    <div class="lengthemployment-value">
        @Html.DisplayFor(model => model.Applications.AppEmploymentLength)
    </div>
    <div class="monthgrossincome">
        <span class="details-span">Monthly Gross Income</span>
    </div>
    <div class="monthgrossincome-value">
        @Model.Applications.AppEmploymentGrossIncome.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us"))
    </div>

    <div class="tenantfullname">
        <span class="details-span">Name of Co-Tenant</span>
    </div>
    <div class="tenantfullname-value">
        @Html.DisplayFor(model => model.Applications.AppTenantFirstName) @Html.DisplayFor(model => model.Applications.AppTenantLastName)
    </div>
    <div class="tenantaddress">
        <span class="details-span">Current Address</span>
    </div>
    <div class="tenantaddress-value">
        @Html.DisplayFor(model => model.Applications.AppTenantAddress) @Html.DisplayFor(model => model.Applications.AppTenantCity) @(Model.Applications.AppTenantState) @Html.DisplayFor(model => model.Applications.AppTenantZipCode)
    </div>
    <div class="tenantdob">
        <span class="details-span">Date of Birth</span>
    </div>
    <div class="tenantdob-value">
        @(Model.Applications.AppTenantDateOfBirth.HasValue ? Model.Applications.AppTenantDateOfBirth.Value.ToString("dd/MM/yyyy") : "")
    </div>
    <div class="tenantphone">
        <span class="details-span">Phone Number</span>
    </div>
    <div class="tenantphone-value">
        @Html.DisplayFor(model => model.Applications.AppTenantPhoneNumber)
    </div>
    <div class="tenantemail">
        <span class="details-span">Email Address</span>
    </div>
    <div class="tenantemail-value">
        @Html.DisplayFor(model => model.Applications.AppTenantEmailAddress)
    </div>

    <div class="tenantemployer">
        <span class="details-span">Name of Employer</span>
    </div>
    <div class="tenantemployer-value">
        @Html.DisplayFor(model => model.Applications.AppTenantEmployerName)
    </div>
    <div class="tenantemployerphone">
        <span class="details-span">Phone Number</span>
    </div>
    <div class="tenantemployerphone-value">
        @Html.DisplayFor(model => model.Applications.AppTenantEmployerNamePhoneNumber)
    </div>
    <div class="tenantlengthemployment">
        <span class="details-span">Length of Employment</span>
    </div>
    <div class="tenantlengthemployment-value">
        @Html.DisplayFor(model => model.Applications.AppTenantLengthOfEmployment)
    </div>
    <div class="tenantmonthlyincome">
        <span class="details-span">Monthly Gross Income</span>
    </div>
    <div class="tenantmonthlyincome-value">
        @(Model.Applications.AppTenantMonthlyGrossIncome.HasValue ? Model.Applications.AppTenantMonthlyGrossIncome.Value.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us")) : "")
    </div>
    <div class="landlord">
        <span class="details-span">Present Landlord</span>
    </div>
    <div class="landlord-value">
        @Html.DisplayFor(model => model.Applications.AppPresentLandlord)
    </div>
    <div class="landlordphone">
        <span class="details-span">Phone Number</span>
    </div>
    <div class="landlordphone-value">
        @Html.DisplayFor(model => model.Applications.AppPresentLandlordPhoneNumber)
    </div>

    <div class="totalpersons">
        <span class="details-span">Total number of persons to occupy apartment</span>
    </div>
    <div class="totalpersons-value">
        @Html.DisplayFor(model => model.Applications.AppTotalPersonsOccupy)
    </div>

    <div class="totalchildren">
        <span class="details-span">Total number of children to occupy apartment</span>
    </div>
    <div class="totalchildren-value">
        @Html.DisplayFor(model => model.Applications.AppTotalChildrenOccupy)
    </div>
    <div class="doyousmoke">
        <span class="details-span">Do you or anyone in your household smoke?</span>
    </div>
    <div class="doyousmoke-value">
        @Html.DisplayFor(model => model.Applications.Smoker.SmokerQuestion)
    </div>
    <div class="doyouhavepets">
        <span class="details-span">Do you or anyone in your household have pets?</span>
    </div>
    <div class="doyouhavepets-value">
        @Html.DisplayFor(model => model.Applications.Pet.PetQuestion)
    </div>
    <div class="haveyoubeenevicted">
        <span class="details-span">Have you or anyone in your household ever been evicted?</span>
    </div>
    <div class="haveyoubeenevicted-value">
        @Html.DisplayFor(model => model.Applications.Eviction.EvictionQuestion)
    </div>
</div>

The line in question is below:

@Html.DisplayFor(model => model.Applications.AppTenantAddress) @Html.DisplayFor(model => model.Applications.AppTenantCity) @(Model.Applications.AppTenantState) @Html.DisplayFor(model => model.Applications.AppTenantZipCode)

Leave a Comment