我的数据库表有50行,如何使用模型在视图上显示所有表?当我试图在视图上显示产品数据时。它显示了表格的最后一行,如何在视图中显示所有行?
//Model : Product Properties
public class AllItems
{
public string ID { get; set; }
public string Name { get; set; }
public string Qty { get; set; }
public string Price { get; set; }
public string ImgName { get; set; }
public string PrdDesc { get; set; }
}
//Controller : Product data action manager
public ActionResult ViewAllItems()
{
string[] Name = new string[10];
DataTable dtProducts = Data.GetAllItems();
for (int i = 0; i < dtProducts.Rows.Count; i++)
{
AllItems allItems = new AllItems
{
ID = dtProducts.Rows[i][0].ToString(),
Name = dtProducts.Rows[i][1].ToString(),
Qty = dtProducts.Rows[i][2].ToString(),
Price = dtProducts.Rows[i][3].ToString(),
PrdDesc = dtProducts.Rows[i][4].ToString(),
};
ViewData["AllItems"] = allItems;
}
return View();
}
//View to show the Product data
@{
AllItems allItems = (AllItems)ViewData["AllItems"];
for (int i = 0; i < 5; i++)
{
<table style="border: 1px solid lightgrey; border-collapse: collapse">
<tr>
<td>
<h3>@allItems.ID</h3>
</td>
<td>
<h3>@allItems.Name</h3>
</td>
<td>
<h3>@allItems.Price</h3>
</td>
<td>
<h3>@allItems.Qty</h3>
</td>
<td>
<h3>@allItems.ImgName</h3>
</td>
<td>
<h3>@allItems.PrdDesc</h3>
</td>
</tr>
<br />
</table>
}
}
有没有办法可以创建模型类的数组并显示属性?
答案 0 :(得分:2)
试试这个。我修改了你的代码以使用模型而不是ViewData。
public class AllItems
{
public string ID { get; set; }
public string Name { get; set; }
public string Qty { get; set; }
public string Price { get; set; }
public string ImgName { get; set; }
public string PrdDesc { get; set; }
}
//Controller : Product data action manager
public ActionResult ViewAllItems()
{
string[] Name = new string[10];
DataTable dtProducts = Data.GetAllItems();
List<AllItems> items = new List<AllItems>();
for (int i = 0; i < dtProducts.Rows.Count; i++)
{
AllItems allItems = new AllItems
{
ID = dtProducts.Rows[i][0].ToString(),
Name = dtProducts.Rows[i][1].ToString(),
Qty = dtProducts.Rows[i][2].ToString(),
Price = dtProducts.Rows[i][3].ToString(),
PrdDesc = dtProducts.Rows[i][4].ToString(),
};
items.Add(allItems);
}
return View(items);
}
//View to show the Product data
@model List<AllItems>
@foreach (var item in model)
{
<table style="border: 1px solid lightgrey; border-collapse: collapse">
<tr>
<td>
<h3>@item.ID</h3>
</td>
<td>
<h3>@item.Name</h3>
</td>
<td>
<h3>@item.Price</h3>
</td>
<td>
<h3>@item.Qty</h3>
</td>
<td>
<h3>@item.ImgName</h3>
</td>
<td>
<h3>@item.PrdDesc</h3>
</td>
</tr>
<br />
</table>
}