我正在使用asp.net核心实体框架。我试图将我的查询结果打印到我的HTML中。这是我的代码。
这是我的.cs
文件
ViewBag.User_Has_Products = (from user_products in _context.Users_Has_Products
join user in _context.Users on user_products.users_id equals user.id
join product in _context.Products on user_products.products_id equals product.id
select new { name = user.name, product = product.name,
quantity = user_products.quanitity, date = user_products.created_at});
foreach(var item in ViewBag.User_Has_Products)
{
System.Console.WriteLine($"{item.name}"); //this output is correct
}
这是我的.cshtml
页面
@{
if(ViewBag.User_Has_Products != null)
{
foreach(var item in ViewBag.User_Has_Products)
{
<p>@$"{item.name}"</p> //trying to print it out here
}
}
}
我也试过<p>@item.name</p>
但是得到一个对象不包含名称错误的定义。
答案 0 :(得分:1)
您不需要.cshtml
文件中的字符串引号,只需按原样使用它,请参阅以下示例:
@{
if(ViewBag.User_Has_Products != null)
{
foreach(var item in ViewBag.User_Has_Products)
{
<p>@item.name</p>
}
}
}
但更好的建议是建立model
并将其发送到view
,如下所示:
public class UserProductsViewmodel() {
public string Name { get; set; }
public string Product { get; set; }
public int Quantity { get; set; }
public string Date { get; set;}
}
并在.cs
文件中使用它,如下所示:
ViewBag.User_Has_Products = (from user_products in _context.Users_Has_Products
join user in _context.Users on user_products.users_id equals user.id
join product in _context.Products on user_products.products_id equals product.id
select new UserProductsViewmodel() {
Name = user.name, Product = product.name,
Quantity = user_products.quanitity, Date = user_products.created_at
});
在你的.cshtml
中这样:
@{
if(ViewBag.User_Has_Products != null)
{
foreach(UserProductsViewmodel item in ViewBag.User_Has_Products)
{
<p>@item.Name</p>
}
}
}
答案 1 :(得分:0)
在Dependency injection into views上查看这篇文章,这比使用ViewBag更好。
控制器操作代码段
public IActionResult GetProducts()
{
var products = (from user_products in _context.Users_Has_Products
join user in _context.Users on user_products.users_id equals user.id
join product in _context.Products on user_products.products_id equals product.id
select new UserProductsViewmodel() {
Name = user.name, Product = product.name,
Quantity = user_products.quanitity, Date = user_products.created_at
});
return View(products);
}
查看摘录(.cshtml)
@model IEnumerable<namespace.ProductModel>
...
@foreach (var item in Model)
{
<p>@item.Bar</p>
}
视图模型
public class ProductModel() {
public string Name { get; set; }
public string Product { get; set; }
public int Quantity { get; set; }
public string Date { get; set;}
}