Search code examples
asp.net-mvcninject.web.mvc

Displaying data from two different model in a view


I am a newbie learning ASP.NET MVC from book.I am using NInject to Implement IoC. I have created a data model for Job and Location as below

Table Name - JobDetails

JobId<PK>
LocationId<FK>
JobName

Table Name - Location

LocationId<PK>
LocationName

I have created Entities for Location and JobDetails as Below

JobDetails

public class JobDetails
{
    [Key]
    public int JOBID { get; set; }

    public int LocationID { get; set; }

    public string JOBNAME { get; set; }
}

Location

public class Location
{
    [Key]
    public int LocationID{ get; set; }

    public string LocationName { get; set; }
}

Also I have my Abstract and Context Class for Job Details and Location as below

public interface IJobDetails
{
    IEnumerable<JobDetails> jobDetailsInterface { get; }
}


public interface ILocation
{

    IEnumerable<Location> locationInterface { get; }
} 

public class EFLocationRepository : ILocation
{
    public  EFDbContext context = new EFDbContext();

    public IEnumerable<Location> locationInterface
    {
        get { return context.Location; }
    }
}

public class EFJobRepository : IJobDetails
{
    public EFDbContext context = new EFDbContext();

    public IEnumerable<JobDetails> jobDetailsInterface
    {
        get { return context.JobDetails; }
    }
}

My Model class for Job and Location are as below

public class JobListViewModel
{
    public IEnumerable<JobDetails> jobDetails { get; set; }
}

public class LocationListViewModel
{
    public IEnumerable<Location> Location { get; set; }
}

In my JobDetail Controller I want to display the location name instead of Location Id. My JobDetail controller is as below

public class JobController : Controller
{
    public IJobDetails repository;

    public JobController(IJobDetails job)
    {
        repository = job;
    }

    public ViewResult List()
    {
        return View(repository.jobDetailsInterface);
    }

}

How to display Location Name instead of Location id in my Job View?

N.B-I am learning MVC from Adam Freeman book and trying to create something new.Please let me know what I have done is correct or not.


Solution

  • Adding to sleeyuen's response. You may want to add a "navigation" property to JobDetails model, like below:

    public class JobDetails
    {
        [Key]
        public int JOBID { get; set; }
    
        public int LocationID { get; set; }
    
        public string JOBNAME { get; set; }
    
        public virtual Location JobLocation { get; set; }
    }
    

    Then you should be able to access Location name from view by doing: repository.jobDetailsInterface.JobLocation.LocationName

    In your scenario I believe entity framework will be able to infer relationships from the model structure, so you won't need entity configuration set up

    Please note, this approach leads to N+1

    Hope this helps :)