Onilol
Onilol

Reputation: 1339

Dealing with multiple models for specific attributes of each in view

I'm trying to display in a table a set of properties specific to each model in n models

I have the following models :

Card

public enum Rarity
{
    Legendary,
    Epic,
    Rare,
    Common
}

public class Card
{
    public int ID { get; set; }

    public string Name { get; set; }
    public bool Disenchant { get; set; }
    public Rarity Rarity { get; set; }

    public virtual ICollection<Deck> Decks { get; set; }
}

Deck

public class Deck
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual Card Card { get; set; }
    public virtual Hero Hero { get; set; }
}

Index Controller of Home:

public ActionResult Index()
{
    var db = new DustContext();
    var cards = db.Cards.ToList();
    return View(cards);
}

Fragments of Index:

@model IEnumerable<App.Models.Card>
<tbody>
  @foreach (var item in Model)
  {
    @Html.Partial("_CardList", item)
    }
</tbody>

and finally my partial :

@model CardApp.Models.Card

<tr>
  <td>@Model.Name</td>
  <td>@Model.Rarity</td>
  <td>@Model.Disenchant</td>
</tr>

How can I display in the table the properties from the card model ( already in the partial ) along with a property from the Deck model ? I've tried using tuples but I was getting List and IEnumerable errors.

Upvotes: 0

Views: 35

Answers (1)

mituw16
mituw16

Reputation: 5250

You should use a ViewModel and have instances of each one of your models in the ViewModel.

Basically, your ViewModel would be what you pass to your view that contains any number of other objects, models, properties, etc etc.

http://sampathloku.blogspot.com/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html

Upvotes: 1

Related Questions