我是MVC5的新人。
我有两张桌子,tblClient
& tblBranch
。
数据结构是:
ID | Name
---------
1 | BCS
2 | LBBI
3 | CARB
ID | cID | BranchName
---------------------
1 | 1 | Savar
2 | 1 | Nobinogor
3 | 2 | Sawrapara
4 | 1 | Mirpur
5 | 3 | Motijheel
6 | 2 | Dhanmondi
7 | 1 | Kazipara
现在我需要在索引页面中显示数据:
sL | Branch
-----------
1 | Savar
2 | Nobinogor
3 | Mirpur
4 | Kazipara
sL | Branch
-----------
1 | Sawrapara
2 | Dhanmondi
sL | Branch
-----------
1 | Motijheel
我该怎么做?
答案 0 :(得分:0)
您可以将每个tblClient包装在新的Object中:
tblClient has name and contains List of tblBranch
public Class Client
{
public string clientName {get;set;}
public List<Branch> branches {get;set;}
}
public Class Branch
{
public string branchName
}
并检索List<Client>
并将其显示给用户界面
答案 1 :(得分:0)
为索引视图编写模型类。
public class MyModel
{
public string GroupName;
public List<string> GroupItems;
}
为您的视图指定模型:
@model IEnumurable<MyProject.MyModel>
@foreach (var item in Model)
{
<h2>@item.GroupName</h2>
<ol>
@foreach (var it in item.GroupItems)
{
<li>@it</li>
}
</ol>
}
最后在控制器的索引操作中填充模型并将其传递给视图:
public ActionResult Index()
{
var model = new List<MyModel>();
var item = new MyModel();
item.GroupName = "Hello World";
item.GroupItems = new List<string>() { "item1", "item2" };
model.Add(item);
return View(model);
}
答案 2 :(得分:0)
没有必要做一些不寻常的事情。特别是,通过灌浆 您可以简单地遍历项目并输出它。
在ASP.NET Razor中:
Dictionary<int, string> clients = // get dictionary from DB like {{1, "BCS"}, {2, "LBBI"} ...}};
List<BranchEntity> branches = // get list of Branch entities just like in DB;
// You can pass these values as ViewBag or together as a Model
@{
foreach (var client in clients)
{
var branchesForClients = branches.Where(x => x.cID == client.Key).ToArray();
<h3>@client.Value</h3>
<table>
for (int i = 0; i < branchesForClients.Length; i++)
{
<tr>
<td>@(i + 1)</td>
<td>@branchesForClients[i].BranchName</td>
</tr>
}
</table>
}
}
这是一个实体:
public class BranchEntity
{
public int Id { get; set; }
public int cId { get; set; }
public string BranchName { get; set; }
}