I want to send data from two existing tables to a view through a controller using EF. Each table has two columns.
ef=> mastername
table=>products,categories
columns => categories_id,categories_name
colmns => products_id,products.name
There is no relationship between the tables
If there is no relationship between two tables, you could create the class as below:
Two class for the product and Category, I assume your dbcontext contains two class for the table.
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
You could create the ViewModel as below to pass two list for two different tables:
public class ProductsCategoriesViewModel
{
public List<Category> Categories { get; set; }
public List<Product> Products { get; set; }
}
The controller:
public class HomeController : Controller
{
private readonly RelaceitwithyourDbContext _context;
public HomeController(RelaceitwithyourDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var categories = _context.Categories.ToList();
var products = _context.Products.ToList();
var viewModel = new ProductsCategoriesViewModel
{
Categories = categories,
Products = products
};
return View(viewModel);
}
}
View:
@model ProductsCategoriesViewModel
<table>
<thead>
<tr>
<th>Category ID</th>
<th>Category Name</th>
</tr>
</thead>
<tbody>
@foreach (var category in Model.Categories)
{
<tr>
<td>@category.CategoryId</td>
<td>@category.CategoryName</td>
</tr>
}
</tbody>
</table>
<table>
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model.Products)
{
<tr>
<td>@product.ProductId</td>
<td>@product.ProductName</td>
</tr>
}
</tbody>
</table>