首页 > 解决方案 > 将 ViewBag 结果绑定到 Html 下拉列表

问题描述

ASP.NET Core MVC 的新功能:尝试绑定 sql 查询的结果(在我的 Controller 上)并添加到 ViewBag 和 Html 下拉列表(下拉列表 B)。Action 方法是基于使用 Ajax 的另一个下拉列表(下拉列表 A)中的更改触发的。

View (if change in dropdown A):

                    $.ajax({
                        type: "POST",
                        url: "/Home/GetBrandsForDropdown",
                        data: null,
                        success: function (result) {
                            alert('Success')
                        },
                        error: function (req, status, error) {
                            alert('No Success')
                        }
                    });
Note: Alert is 'No Success" when I run it.

Controller:
        public IActionResult GetBrandsForDropdown()
        {
            var content = from b in Context.Brands
                          select new { b.BrandNumber, b.BrandName };

            ViewBag.BrandListing = content.Select(c => new SelectListItem
                {
                    Text = c.BrandName,
                    Value = c.BrandNumber.ToString()
                }).ToList();
                                   
            return View();
        }
Note: ViewBag.BrandListing includes values when I debug.

尝试将 ViewBag 中的值转换为以下内容但未成功:

<select class="dropdown form-control" onchange="getOption()" name="brandDDL" 
id="ddlBrandName"style="background-color: #E6E6E6;
                        font-size: small; color: black; font-weight: bold;
                        border: double">

这似乎是应该很容易解决的问题,但我没有运气得到我想要的结果。

任何/所有帮助将不胜感激。杰克

标签: asp.netasp.net-coreviewbag

解决方案


一个简单的方法是遍历 viewbag;

<select class="dropdown form-control" onchange="getOption()" name="brandDDL" id="ddlBrandName"style="background-color: #E6E6E6; font-size: small; color: black; font weight: bold; border: double">
@foreach(var item in ViewBag.BrandListing){
   <option value="@item.Value">@item.Text</option>
}
</select>

推荐阅读