Reputation: 1951
How would I create a model to store multiple complex object types,be strongly typed, and scalable for more complex object types in the future?
???
represents where the class should be but not sure of what to make it.
The big caveat in this would be that the list should be able to be mixed so I think just wrapping List<>'s of each complex type won't work
I.e. Output
Sample code
// Models
public class Fruit
{
string Name {get;set}
bool IsSweet {get;set}
}
public class Vegetable
{
string Name {get;set}
bool IsGross {get;set}
}
// Controller Action
public ActionResult ViewFood(int userId)
{
??? foods = GetFood(userId);
return View(foods);
}
// View
@model List<???>
<ul>
@foreach(var item in model)
{
if(item is Fruit)
{
<li>@Name - @IsSweet</li>
}
else if(item is Vegetable)
{
<li>@Name - @IsGross</li>
}
}
</ul>
// Buisness Layer
public ??? GetFood(int userId)
{
var fruits = repo.Get<Fruit>(f => f.UserId == userId).ToList();
var vegatbles = repo.Get<Vegetable>(v => v.UserId == userId).ToList();
return ???
}
Upvotes: 0
Views: 80
Reputation: 274358
You can create a common base class for Fruit
and Vegetable
- Food
:
class Food {
public String Name { get; set; }
}
class Fruit : Food {
public bool IsSweet { get; set; }
}
class Vegetable : Food {
public bool IsGross { get; set; }
}
Replace all your ???
with Food
.
Alternatively, use dynamic
.
Upvotes: 4