将2个表合并为1个选择列表

时间:2019-01-17 06:44:13

标签: asp.net-core

我想问吗? 我只是做选择列表,但我想我的选择列表提供2表。 在我的Chartaccount表格中

+---------+---------+
|Kodeakun |Namaakun |
--------------------|
|10000    |Asset    |
|20000    |Utang    |
|30000    |Modal    |
+-------------------+

在我的控制器中

public IActionResult Create()`
{
List<ChartAccount> categorylist = new List<ChartAccount>();
categorylist = (from category in _context.ChartAccount select category).ToList();
categorylist.Insert(0, new ChartAccount { Id = 0, Kodeakun = 0, Namaakun = "Select", Saldo = 0 });
ViewBag.listofcategory = categorylist;
return View();
}

在我看来

<select asp-for="Kodeakun" class="form-control" asp-items="@(new SelectList(@ViewBag.listofcategory,"Kodeakun","Namaakun"))"></select>

我尝试但没有成功

<select asp-for="Kodeakun" class="form-control" asp-items="@(new SelectList(@ViewBag.listofcategory,"Kodeakun","Kodeakun"+"Namaakun"))"></select>

1 个答案:

答案 0 :(得分:0)

尝试像

一样在10000 Asset中返回ViewBag.listofcategory
List<ChartAccount> categorylist = new List<ChartAccount>() {
    new ChartAccount{ Id = 1, Kodeakun = 10000, Namaakun = "K1"},
    new ChartAccount{ Id = 2, Kodeakun = 20000, Namaakun = "K2"},
    new ChartAccount{ Id = 3, Kodeakun = 30000, Namaakun = "K3"}
};
var categorySelectList = categorylist.Select(c => {
    return new { Key = c.Id , Value = c.Kodeakun + " " + c.Namaakun  };
}).ToList();
categorySelectList.Insert(0, new { Key = 0, Value = "Select" });

ViewBag.listofcategory = categorySelectList;

查看方式

<select class="form-control" asp-items="@(new SelectList(@ViewBag.listofcategory,"Key","Value"))"></select>