Reputation: 2711
I have created two different tables with entity. The code looks like this:
public class Frisorer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Scheman> Schema { get; set; }
}
public class Scheman
{
public int Id { get; set; }
public DateTime Schemat { get; set; }
public virtual Frisorer frisorer { get; set; }
}
My context file:
public class Context : DbContext
{
public Context()
: base("DefaultConnection")
{
}
public DbSet<Frisorer> Frisorer { get; set; }
public DbSet<Scheman> Scheman { get; set; }
}
The tables get created allright with keys establishing a relationship between them. What i would like now is to be able to display both the names/id of my frisor and their schemas in the same view in MVC. But when i try to add a view, I can only choose strongly typed views with either Frisorer OR Schemas...How can I do to display both my tables together?
EDIT:
I created a new class where I encaosulated the two other classes:
public class Frisorer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Scheman> Schema { get; set; }
}
public class Scheman
{
public int Id { get; set; }
public DateTime Schemat { get; set; }
public virtual Frisorer frisorer { get; set; }
}
public class BigViewModel
{
public List<Frisorer> Frisorer { get; set; }
public List<Scheman> Scheman { get; set; }
}
And the controll:
public ActionResult hopp()
{
BigViewModel bv = new BigViewModel();
bv.Frisorer = (from o in cont.Frisorer select o).ToList();
bv.Scheman = (from or in cont.Scheman select or).ToList();
return View(bv);
}
I create a view where I choose BigViewModel as the strongly typed and list as scaffolding. Get this error: The model item passed into the dictionary is of type 'MvcApplication3.Models.BigViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MvcApplication3.Models.BigViewModel]'
Upvotes: 1
Views: 136
Reputation: 630
You are getting the exception because you are passing an single object
to the view when the view is expecting a collection of BigViewModel
.
Try changeing the modelbinding in your view to: @model BigViewModel
instead of @model IEnumerable<BigViewModel>
and then iterate the collections in your Model
:
@foreach(var frisor in Model.Frisorer)
{
//do stuff
}
@foreach(var schema in Model.Scheman)
{
//do stuff
}
Upvotes: 1
Reputation: 11448
You just need to change the model in the view from @model IEnumerable<BigViewModel>
to @model BigViewModel
and then iterate over Frisorer
and Scheman
, something like so:
@model BigViewModel
<ul>
@foreach(var item in Model.Frisorer)
{
<li>@item.Id - @item.Name</li>
}
</ul>
<ul>
@foreach(var item in Model.Scheman)
{
<li>@item.Id - @item.Schemat</li>
}
</ul>
Upvotes: 1
Reputation: 13600
Create a third class, some kind of a ViewModel/Wrapper, that will encapsulate everything you need. Reference it then in your View.
Upvotes: 1