带有Razor的ASP.NET Core 2:填充选择列表

时间:2018-03-20 12:36:26

标签: asp.net-core-2.0

我正在尝试从viewbag填充选择列表,但它没有填充。我在viewbag中有68个项目(使用断点)所以我知道数据存在。我显然使用错误的格式从viewbag获取数据。我的问题可能是

asp-for="CountyId"

这是我的代码......

CHTML

<select asp-for="CountyId" data-live-search="true" class="selectpicker" asp-items="@(new SelectList(ViewBag.ListofCounty, "CountyId", "CountyName"))"></select>

控制器

    public IActionResult Index(TblCounty TblCounty) {
        List<TblCounty> countylist = new List<TblCounty>();

        // ----------- Getting Data from Database Using Entity FrameworkCore ----------- //
        countylist = (from product in _context.TblCounty
                      select product).ToList();

        // ----------- Inserting Select Item in List ----------- //
        countylist.Insert(0, new TblCounty { CountyId = 0, CountyName = "Select" });

        // ----------- Assigning countylist to View.ListofCounty ----------- //
        ViewBag.ListofCounty = countylist;

        return View();
    }

1 个答案:

答案 0 :(得分:0)

这可能不是最好的方法,但效果很好!

evt