[SOLVED] How to display data from two separate tables in MVC?

Issue

So, i am new to programming and i am trying to make my first .net project, and i’m stuck.

I have a database that contains table Product, it looks like this:

    [Key]
    public int ProductId { get; set; }

    public string ProductName { get; set; }

    [Range(1, int.MaxValue)]
    public double ProductPrice { get; set; }

    public string ProductDescription { get; set; }

    public string ProductImagePath { get; set; }
   
    public int ProductColorId { get; set; }
    [ForeignKey("ProductColorId")]
    public virtual ProductColor ProductColor { get; set; }

   
    public int ProductShippingOptionId { get; set; }
    [ForeignKey("ProductShippingOptionId")]
    public virtual ProductShippingOption ProductShippingOption { get; set; }

    
    
    public int ProductConditionId { get; set; }
    [ForeignKey("ProductConditionId")]
    public virtual ProductCondition ProductCondition { get; set; }

Columns ProductShippingOption, ProductColor and ProductCondition are a separate tables that each contain columns for Id and Name.

When i add a product to database, i want to show details of just one product in a view, but i need to display ProductConditionName instead of ProductConditionId (for example).

What should i include in my ViewModel and my Controller so i can use it in my View?

My action in a ProductController looks like this

public IActionResult ProductTemplate(int? id)
    {
        ProductVM productVM = new ProductVM()
        {
            Product = _db.Product.Find(id),
            
        };

        if (id == 0)
        {
            return NotFound();
        }

        if (id == 0)
        {
            return NotFound();
        }

       

        if(productVM==null)
        {
            return NotFound();
        }

        return View(productVM);

    }

Thanks!

Solution

Best and easiest way to do it is including the classes in Product:

For your ProductTemplate action :

ProductVM productVM = new ProductVM()
{


    Product = _db.Product.Where(s=>s.Id == id)
                         .Include(s=>s.ProductColor)
                         .Include(s=>s.ProductShippingOption)
                         .Include(s=>s.ProductCondition)
                         .FirstOrDefault();
};

And you can call them in your .cshtml with (Let say you want ProductColor name) :

@Model.Product.ProductColor.Name

Alternatively you can add Include() to your context to take all includes defaultly.

Answered By – AsIndeed

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *