Search code examples
c#asp.netsqlasp.net-mvcasp.net-mvc-4

Passing a List through the controller into the IEnumerable view ASP.NET MVC 4


I have connected sub-category tables to the main table in my models. A structure similar to the one below.

Structure of my sql

However, I need to access information from different tables (sub-tables) into my main table, Article. So I have written additional code into my ArticleController in the Index method as shown here:

    public ActionResult Index()
    {
        var articles = db.DataToArticles
                         .Include(a => a.AgeGroup)
                         .Include(a => a.Disabilities)
                         .Include(a => a.StrategyType);

        return View(articles.ToList());
    } 

DataToArticles is similar to the StrategyTypeToArticle table above.

Here is my data access layer, which I haven't had any issues with:

public class ArticleEntities : DbContext
{
    public DbSet<AgeGroup> AgeGroups { get; set; }
    public DbSet<Disabilities> Disabilitiess { get; set; }
    public DbSet<StrategyType> StrategyTypes { get; set; }
    public DbSet<Article> Articles { get; set; }
    public DbSet<UserProfile> Profiles { get; set; }
    public DbSet<DataToArticle> DataToArticles { get; set; }
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    }
}

Now here's my view, which is causing an error:

@model IEnumerable<LearningEnterprises.Models.Article>

The problem

The issue is passing the articles variable in the controller to my view IEnumerable. I know it is passing it as a list, but I haven't had issues with this before. Is there a way around this?


Solution

  • Because you're querying db.DataToArticles, you are passing an IEnumerable<LearningEnterprises.Models.DataToArticle> to the view rather than an IEnumerable<LearningEnterprises.Models.Article>.