简体   繁体   中英

MVC Combine data from two different tables into one view

Lately I have been trying to get into MVC. I finished the MVC tutorial on the asp.net website of Microsoft. Now that I am trying to figure out how I should apply the following database design in a model class (C#) code of the application I am working on, I am experiencing certain trouble.

I want to know how I can add a ProductCategory to my model:

数据库设计

My model class:

namespace myprojectname.Models
{
    public class ShoppingCartItems
    {
        public virtual int ID { get; set; }
        [Required]
        [Display(Name="Product name")]
        public virtual string ProductName { get; set; }
        //[Display(Name="Category")]
        //public virtual int CategoryName { get; set; }
        [Display(Name="Date")]
        public virtual DateTime DateAdded { get; set; }
        [Required]
        [DataType(DataType.Currency)]
        public virtual decimal ProductPrice { get; set; }
        public virtual int AmountAvailable { get; set; }
    }
}

ShoppingCartItems is what should displays all entries of the products table. As far as I know it should be possible to scaffold all of the tables and display all of the products with categories on one page.

Can anyone explain me how such MVC model class (or do I need to add a query to the controller class?) would need to look like in order to show categories on the index view belonging to the products displayed? Should I need to make an object of type Categories and add it to my properties?

Yes, you should create a class for Category. Then your Product class should have a List property.

When you pass your list of products to your View they will know which categories they have.

Without more information on the Data Layer technology you are using I can't give more examples sorry.

You can simply create ViewModel class. Create one folder in your project and in this folder create one class.

public class ViewModel
{
    public Product Product { get; set; }
    public IEnumerable<Product> Products { get; set; }

    public Genre Category { get; set; }
    public IEnumerable<Genre> Categories{ get; set; }
}

And then in your action you can call your ViewModel class.

public ActionResult ExampleClass()
{
        var viewModel = new ViewModel
        {
            Products = db.Products.ToList(), //you can also call just one product here
            Categories = db.Categories .ToList() //same here
        };

        return View(viewModel);;
}

View:

@model Injuriesp.ViewModels.ViewModel

I'm first here and I hope this helps: For example product model is:

[Table("Products")]
public class Product
{
    [Key]
    public string Id { get; set; }
    [Required]
    public string Name { get; set; }
}

Category model:

[Table("Categories")]
public class Category
{
    [Key]
    public string Id { get; set; }
    [Required]
    public string Name { get; set; }
}

Product category model:

[Table("ProductCategories")]
public class ProductCategory
{
    [Key]
    [Column(Order = 0)]
    public string ProductId { get; set; }
    [Key]
    [Column(Order = 1)]
    public string CategoryId { get; set; }
    public virtual Category Category { get; set; }
}

You need add ViewModel:

public class ProductDetailsViewModel
{
    public virtual Product Product { get; set; }
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

Now example of "Details" part of controller:

// GET: Products/Details/5
    public async Task<ActionResult> Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Product product = await db.Products.FindAsync(id);
        if (product == null)
        {
            return HttpNotFound();
        }
        ProductDetailsViewModel model = new ProductDetailsViewModel()
        {
            Product = await db.Products.SingleOrDefaultAsync(x => x.Id == id),
            ProductCategories = await db.ProductCategories.Where(x => x.ProductId == id).ToListAsync()
        };
        return View(model);
    }

So finaly Details View:

@model YourApplicationName.Models.ProductDetailsViewModel



<hr />
<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor(model => model.Product.AddedAt)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Product.AddedAt)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Product.Name)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Product.Name)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Product.Description)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Product.Description)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Product.InwearhouseQuantity)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Product.InwearhouseQuantity)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Product.InternalPrice)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Product.InternalPrice)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Product.ExternalPrice)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Product.ExternalPrice)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Product.Published)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Product.Published)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Product.Url)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Product.Url)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.ProductCategories)
    </dt>
    <dd>
        <table class="table">
            <tr>
                <th>Category</th>
                <th>Description</th>
            </tr>
            @foreach (var item in Model.ProductCategories)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category.Description)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category.Url)
                    </td>
                </tr>
            }
        </table>
    </dd>
</dl>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM